diff --git a/src/Chapter01/Listing01.03.MultipleStatementsOneOneLine.cs b/src/Chapter01/Listing01.03.MultipleStatementsOneOneLine.cs index bc0376b14..b4ea21b77 100644 --- a/src/Chapter01/Listing01.03.MultipleStatementsOneOneLine.cs +++ b/src/Chapter01/Listing01.03.MultipleStatementsOneOneLine.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_03; + +public class HelloWorld { - public class HelloWorld + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.WriteLine("Up"); Console.WriteLine("Down"); - #endregion INCLUDE - } + #region INCLUDE + Console.WriteLine("Up"); Console.WriteLine("Down"); + #endregion INCLUDE } } diff --git a/src/Chapter01/Listing01.04.MultipleStatementsOnSeparateLines.cs b/src/Chapter01/Listing01.04.MultipleStatementsOnSeparateLines.cs index c7040c245..3a6954fa5 100644 --- a/src/Chapter01/Listing01.04.MultipleStatementsOnSeparateLines.cs +++ b/src/Chapter01/Listing01.04.MultipleStatementsOnSeparateLines.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_04; + +public class HelloWorld { - public class HelloWorld + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.WriteLine("Down"); - Console.WriteLine("Side"); - Console.WriteLine("Up"); - #endregion INCLUDE - } + #region INCLUDE + Console.WriteLine("Down"); + Console.WriteLine("Side"); + Console.WriteLine("Up"); + #endregion INCLUDE } } diff --git a/src/Chapter01/Listing01.05.SplittingAStatementAcrossMultipleLines.cs b/src/Chapter01/Listing01.05.SplittingAStatementAcrossMultipleLines.cs index dd30d8921..74ea19394 100644 --- a/src/Chapter01/Listing01.05.SplittingAStatementAcrossMultipleLines.cs +++ b/src/Chapter01/Listing01.05.SplittingAStatementAcrossMultipleLines.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_05; + +public class HelloWorld { - public class HelloWorld + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.WriteLine( - "Hello. My name is Inigo Montoya."); - #endregion INCLUDE - } + #region INCLUDE + Console.WriteLine( + "Hello. My name is Inigo Montoya."); + #endregion INCLUDE } } diff --git a/src/Chapter01/Listing01.06.HelloWorldInC#.cs b/src/Chapter01/Listing01.06.HelloWorldInC#.cs index 79fcd62be..466435c79 100644 --- a/src/Chapter01/Listing01.06.HelloWorldInC#.cs +++ b/src/Chapter01/Listing01.06.HelloWorldInC#.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_06; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - System.Console.WriteLine("Hello. My name is Inigo Montoya."); - } + System.Console.WriteLine("Hello. My name is Inigo Montoya."); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.07.BasicClassDeclaration.cs b/src/Chapter01/Listing01.07.BasicClassDeclaration.cs index 20c646c2b..973389297 100644 --- a/src/Chapter01/Listing01.07.BasicClassDeclaration.cs +++ b/src/Chapter01/Listing01.07.BasicClassDeclaration.cs @@ -1,9 +1,8 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_07; + +#region INCLUDE +public class HelloWorld { - #region INCLUDE - public class HelloWorld - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.08.BreakingApartHelloWorld.cs b/src/Chapter01/Listing01.08.BreakingApartHelloWorld.cs index 32f606294..ac23cc2bd 100644 --- a/src/Chapter01/Listing01.08.BreakingApartHelloWorld.cs +++ b/src/Chapter01/Listing01.08.BreakingApartHelloWorld.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_08; + +#region INCLUDE +public class Program // BEGIN Class definition { - #region INCLUDE - public class Program // BEGIN Class definition - { - public static void Main() // Method declaration - { // BEGIN method implementation - Console.WriteLine( // This statement spans 2 lines - "Hello, My name is Inigo Montoya"); - } // END method implementation - } // END class definition - #endregion INCLUDE -} + public static void Main() // Method declaration + { // BEGIN method implementation + Console.WriteLine( // This statement spans 2 lines + "Hello, My name is Inigo Montoya"); + } // END method implementation +} // END class definition +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.09.TheMainMethodWithParametersAndAReturn.cs b/src/Chapter01/Listing01.09.TheMainMethodWithParametersAndAReturn.cs index e1af597ad..c722e70a1 100644 --- a/src/Chapter01/Listing01.09.TheMainMethodWithParametersAndAReturn.cs +++ b/src/Chapter01/Listing01.09.TheMainMethodWithParametersAndAReturn.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_09; + +public class Program { - public class Program + #region INCLUDE + public static int Main(string[] args) { - #region INCLUDE - public static int Main(string[] args) - { - #region EXCLUDE - return 0; - #endregion EXCLUDE - } - #endregion INCLUDE + #region EXCLUDE + return 0; + #endregion EXCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter01/Listing01.10.NoIndentationFormatting.cs b/src/Chapter01/Listing01.10.NoIndentationFormatting.cs index ef9755445..23df37a19 100644 --- a/src/Chapter01/Listing01.10.NoIndentationFormatting.cs +++ b/src/Chapter01/Listing01.10.NoIndentationFormatting.cs @@ -1,5 +1,5 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_10 -{ +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_10; + #region INCLUDE public class HelloWorld { @@ -9,4 +9,3 @@ public static void Main() } } #endregion INCLUDE -} diff --git a/src/Chapter01/Listing01.12.DeclaringAndAssigningAVariable.cs b/src/Chapter01/Listing01.12.DeclaringAndAssigningAVariable.cs index 3935219bd..a6fd23523 100644 --- a/src/Chapter01/Listing01.12.DeclaringAndAssigningAVariable.cs +++ b/src/Chapter01/Listing01.12.DeclaringAndAssigningAVariable.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_12; + +#region INCLUDE +public class MiracleMax { - #region INCLUDE - public class MiracleMax + public static void Main() { - public static void Main() - { - string max; // "string" identifies the data type - // "max" is the variable - max = "Have fun storming the castle!"; - Console.WriteLine(max); - } + string max; // "string" identifies the data type + // "max" is the variable + max = "Have fun storming the castle!"; + Console.WriteLine(max); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.13.DeclaringTwoVariablesWithinOneStatement.cs b/src/Chapter01/Listing01.13.DeclaringTwoVariablesWithinOneStatement.cs index 482a46a61..656bd9041 100644 --- a/src/Chapter01/Listing01.13.DeclaringTwoVariablesWithinOneStatement.cs +++ b/src/Chapter01/Listing01.13.DeclaringTwoVariablesWithinOneStatement.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_13; + +public class HelloWorld { - public class HelloWorld + public static void Main() { - public static void Main() - { - #region INCLUDE - string message1, message2; - #endregion INCLUDE + #region INCLUDE + string message1, message2; + #endregion INCLUDE - message1 = "My name is Inigo Montoya.";; - message2 = "You killed my father...."; + message1 = "My name is Inigo Montoya.";; + message2 = "You killed my father...."; - Console.WriteLine(message1); - Console.WriteLine(message2); - } + Console.WriteLine(message1); + Console.WriteLine(message2); } } diff --git a/src/Chapter01/Listing01.14.ChangingTheValueOfAVariable.cs b/src/Chapter01/Listing01.14.ChangingTheValueOfAVariable.cs index 3d9f8d567..970464246 100644 --- a/src/Chapter01/Listing01.14.ChangingTheValueOfAVariable.cs +++ b/src/Chapter01/Listing01.14.ChangingTheValueOfAVariable.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_14; + +#region INCLUDE +public class StormingTheCastle { - #region INCLUDE - public class StormingTheCastle + public static void Main() { - public static void Main() - { - string valerie; - #region HIGHLIGHT - string miracleMax = "Have fun storming the castle!"; + string valerie; + #region HIGHLIGHT + string miracleMax = "Have fun storming the castle!"; - valerie = "Think it will work?"; - #endregion HIGHLIGHT + valerie = "Think it will work?"; + #endregion HIGHLIGHT - Console.WriteLine(miracleMax); - Console.WriteLine(valerie); + Console.WriteLine(miracleMax); + Console.WriteLine(valerie); - #region HIGHLIGHT - miracleMax = "It would take a miracle."; - #endregion HIGHLIGHT - Console.WriteLine(miracleMax); - } + #region HIGHLIGHT + miracleMax = "It would take a miracle."; + #endregion HIGHLIGHT + Console.WriteLine(miracleMax); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.15.AssignmentReturningAValueThatCanBeassignedAgain.cs b/src/Chapter01/Listing01.15.AssignmentReturningAValueThatCanBeassignedAgain.cs index 850dcbcb4..55132e236 100644 --- a/src/Chapter01/Listing01.15.AssignmentReturningAValueThatCanBeassignedAgain.cs +++ b/src/Chapter01/Listing01.15.AssignmentReturningAValueThatCanBeassignedAgain.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_15; + +#region INCLUDE +public class StormingTheCastle { - #region INCLUDE - public class StormingTheCastle + public static void Main() { - public static void Main() - { - // ... - string requirements, miracleMax; - requirements = miracleMax = "It would take a miracle."; - #region EXCLUDE - Console.WriteLine(miracleMax); - #endregion EXCLUDE - } + // ... + string requirements, miracleMax; + requirements = miracleMax = "It would take a miracle."; + #region EXCLUDE + Console.WriteLine(miracleMax); + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.16.UsingSystemConsoleReadLine.cs b/src/Chapter01/Listing01.16.UsingSystemConsoleReadLine.cs index 6184fe6e9..7e934a91f 100644 --- a/src/Chapter01/Listing01.16.UsingSystemConsoleReadLine.cs +++ b/src/Chapter01/Listing01.16.UsingSystemConsoleReadLine.cs @@ -1,21 +1,20 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_16; + +#region INCLUDE +public class HeyYou { - #region INCLUDE - public class HeyYou + public static void Main() { - public static void Main() - { - string firstName; - string lastName; + string firstName; + string lastName; - Console.WriteLine("Hey you!"); + Console.WriteLine("Hey you!"); - Console.Write("Enter your first name: "); - firstName = Console.ReadLine(); + Console.Write("Enter your first name: "); + firstName = Console.ReadLine(); - Console.Write("Enter your last name: "); - lastName = Console.ReadLine(); - } + Console.Write("Enter your last name: "); + lastName = Console.ReadLine(); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.17.UsingSystemConsoleRead.cs b/src/Chapter01/Listing01.17.UsingSystemConsoleRead.cs index 6cc9d5673..c1804f5a2 100644 --- a/src/Chapter01/Listing01.17.UsingSystemConsoleRead.cs +++ b/src/Chapter01/Listing01.17.UsingSystemConsoleRead.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_17; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int readValue; - char character; - readValue = Console.Read(); - character = (char) readValue; - Console.Write(character); - #endregion INCLUDE - } + #region INCLUDE + int readValue; + char character; + readValue = Console.Read(); + character = (char) readValue; + Console.Write(character); + #endregion INCLUDE } } diff --git a/src/Chapter01/Listing01.18.FormattingUsingStringInterpolation.cs b/src/Chapter01/Listing01.18.FormattingUsingStringInterpolation.cs index 5b2a320e5..4af32698e 100644 --- a/src/Chapter01/Listing01.18.FormattingUsingStringInterpolation.cs +++ b/src/Chapter01/Listing01.18.FormattingUsingStringInterpolation.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_18; + +#region INCLUDE +public class HeyYou { - #region INCLUDE - public class HeyYou + public static void Main() { - public static void Main() - { - string firstName; - string lastName; + string firstName; + string lastName; - Console.WriteLine("Hey you!"); + Console.WriteLine("Hey you!"); - Console.Write("Enter your first name: "); - firstName = Console.ReadLine(); + Console.Write("Enter your first name: "); + firstName = Console.ReadLine(); - Console.Write("Enter your last name: "); - lastName = Console.ReadLine(); + Console.Write("Enter your last name: "); + lastName = Console.ReadLine(); - Console.WriteLine( - #region HIGHLIGHT - $"Your full name is { firstName } { lastName }."); - #endregion HIGHLIGHT - } + Console.WriteLine( + #region HIGHLIGHT + $"Your full name is { firstName } { lastName }."); + #endregion HIGHLIGHT } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.19.FormattingUsingCompositeFormatting.cs b/src/Chapter01/Listing01.19.FormattingUsingCompositeFormatting.cs index 88ef16dbd..ba9ae7b12 100644 --- a/src/Chapter01/Listing01.19.FormattingUsingCompositeFormatting.cs +++ b/src/Chapter01/Listing01.19.FormattingUsingCompositeFormatting.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_19; + +#region INCLUDE +public class HeyYou { - #region INCLUDE - public class HeyYou + public static void Main() { - public static void Main() - { - string firstName; - string lastName; + string firstName; + string lastName; - Console.WriteLine("Hey you!"); + Console.WriteLine("Hey you!"); - Console.Write("Enter your first name: "); - firstName = Console.ReadLine(); + Console.Write("Enter your first name: "); + firstName = Console.ReadLine(); - #region HIGHLIGHT - Console.Write("Enter your last name: "); - lastName = Console.ReadLine(); - #endregion HIGHLIGHT + #region HIGHLIGHT + Console.Write("Enter your last name: "); + lastName = Console.ReadLine(); + #endregion HIGHLIGHT - Console.WriteLine( - "Your full name is {0} {1}.", firstName, lastName); - } + Console.WriteLine( + "Your full name is {0} {1}.", firstName, lastName); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter01/Listing01.20.SwappingTheIndexedPlaceholdersAndCorrespondingVariables.cs b/src/Chapter01/Listing01.20.SwappingTheIndexedPlaceholdersAndCorrespondingVariables.cs index e7b2b345b..4ee9fc975 100644 --- a/src/Chapter01/Listing01.20.SwappingTheIndexedPlaceholdersAndCorrespondingVariables.cs +++ b/src/Chapter01/Listing01.20.SwappingTheIndexedPlaceholdersAndCorrespondingVariables.cs @@ -1,22 +1,21 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_20; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - string firstName; - string lastName; + string firstName; + string lastName; - Console.WriteLine("Hey you!"); + Console.WriteLine("Hey you!"); - Console.Write("Enter your first name: "); - firstName = Console.ReadLine(); + Console.Write("Enter your first name: "); + firstName = Console.ReadLine(); - Console.Write("Enter your last name: "); - lastName = Console.ReadLine(); - #region INCLUDE - Console.WriteLine("Your full name is {1}, {0}.", firstName, lastName); - #endregion INCLUDE - } + Console.Write("Enter your last name: "); + lastName = Console.ReadLine(); + #region INCLUDE + Console.WriteLine("Your full name is {1}, {0}.", firstName, lastName); + #endregion INCLUDE } } diff --git a/src/Chapter01/TopLevelStatementWrapperForListing01.01.cs b/src/Chapter01/TopLevelStatementWrapperForListing01.01.cs index 581ef71f1..a571ab0d7 100644 --- a/src/Chapter01/TopLevelStatementWrapperForListing01.01.cs +++ b/src/Chapter01/TopLevelStatementWrapperForListing01.01.cs @@ -1,16 +1,15 @@ // See https://aka.ms/new-console-template for more information // this file redirects debug break points to Listing01.01.HelloWorldInC#.cs // allowing for the appearance that the top-level statement file of Listing01.01.HelloWorldInC#.cs is what is being ran. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter01.Listing01_01; + +public class HelloWorld { - public class HelloWorld + public static void Main() { - public static void Main() - { - // the #line directive reroutes the debugger's line mapper from this file to "Listing01.01.HelloWorldInC#.cs" - // see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives#error-and-warning-information + // the #line directive reroutes the debugger's line mapper from this file to "Listing01.01.HelloWorldInC#.cs" + // see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives#error-and-warning-information #line (3,1) - (3,55) 13 "Listing01.01.HelloWorldInC#.cs" - Console.WriteLine("Hello. My name is Inigo Montoya."); - } + Console.WriteLine("Hello. My name is Inigo Montoya."); } } \ No newline at end of file diff --git a/src/Chapter03/Listing03.01.CheckingForNull.cs b/src/Chapter03/Listing03.01.CheckingForNull.cs index a6934b2d8..0c5cb006d 100644 --- a/src/Chapter03/Listing03.01.CheckingForNull.cs +++ b/src/Chapter03/Listing03.01.CheckingForNull.cs @@ -1,29 +1,28 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_01; + +public class Program { - public class Program + #region INCLUDE + public static void Main(string[] args) { - #region INCLUDE - public static void Main(string[] args) + int? number = null; + #region EXCLUDE + if (args.Length>0) + { + number = args[0].Length; + } + #endregion EXCLUDE + if (number is null) + { + Console.WriteLine( + "'number' requires a value and cannot be null"); + } + else { - int? number = null; - #region EXCLUDE - if (args.Length>0) - { - number = args[0].Length; - } - #endregion EXCLUDE - if (number is null) - { - Console.WriteLine( - "'number' requires a value and cannot be null"); - } - else - { - Console.WriteLine( - $"'number' doubled is { number * 2 }."); - } + Console.WriteLine( + $"'number' doubled is { number * 2 }."); } - #endregion INCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter03/Listing03.02.DereferencingAnUnassignedVariable.cs b/src/Chapter03/Listing03.02.DereferencingAnUnassignedVariable.cs index c03303fc6..63d61f6a8 100644 --- a/src/Chapter03/Listing03.02.DereferencingAnUnassignedVariable.cs +++ b/src/Chapter03/Listing03.02.DereferencingAnUnassignedVariable.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_02; + +public class Program { - public class Program + #region INCLUDE + #nullable enable + public static void Main() { - #region INCLUDE - #nullable enable - public static void Main() - { - #if COMPILEERROR // EXCLUDE - string? text; - // ... - // Compile Error: Use of unassigned local variable 'text' - System.Console.WriteLine(text.Length); - #endif // COMPILEERROR // EXCLUDE - } - #endregion INCLUDE -} + #if COMPILEERROR // EXCLUDE + string? text; + // ... + // Compile Error: Use of unassigned local variable 'text' + System.Console.WriteLine(text.Length); + #endif // COMPILEERROR // EXCLUDE + } + #endregion INCLUDE } diff --git a/src/Chapter03/Listing03.03.WorkingWithStrings.cs b/src/Chapter03/Listing03.03.WorkingWithStrings.cs index f2e8df824..145c89733 100644 --- a/src/Chapter03/Listing03.03.WorkingWithStrings.cs +++ b/src/Chapter03/Listing03.03.WorkingWithStrings.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_03; + +public class Uppercase { - public class Uppercase + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.Write("Enter text: "); - var text = Console.ReadLine(); + #region INCLUDE + Console.Write("Enter text: "); + var text = Console.ReadLine(); - // Return a new string in uppercase - var uppercase = text.ToUpper(); + // Return a new string in uppercase + var uppercase = text.ToUpper(); - Console.WriteLine(uppercase); - #endregion INCLUDE - } + Console.WriteLine(uppercase); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.05.ImplicitLocalVariablesWithAnonymousTypes.cs b/src/Chapter03/Listing03.05.ImplicitLocalVariablesWithAnonymousTypes.cs index 4b177df02..beb27df39 100644 --- a/src/Chapter03/Listing03.05.ImplicitLocalVariablesWithAnonymousTypes.cs +++ b/src/Chapter03/Listing03.05.ImplicitLocalVariablesWithAnonymousTypes.cs @@ -1,22 +1,21 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_05; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - var patent1 = - new { Title = "Bifocals", - YearOfPublication = "1784" }; - var patent2 = - new { Title = "Phonograph", - YearOfPublication = "1877" }; + #region INCLUDE + var patent1 = + new { Title = "Bifocals", + YearOfPublication = "1784" }; + var patent2 = + new { Title = "Phonograph", + YearOfPublication = "1877" }; - Console.WriteLine( - $"{patent1.Title} ({patent1.YearOfPublication})"); - Console.WriteLine( - $"{patent2.Title} ({patent2.YearOfPublication})"); - #endregion INCLUDE - } + Console.WriteLine( + $"{patent1.Title} ({patent1.YearOfPublication})"); + Console.WriteLine( + $"{patent2.Title} ({patent2.YearOfPublication})"); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.06.DeclaringAnArray.cs b/src/Chapter03/Listing03.06.DeclaringAnArray.cs index 5e1e2e23b..72c607363 100644 --- a/src/Chapter03/Listing03.06.DeclaringAnArray.cs +++ b/src/Chapter03/Listing03.06.DeclaringAnArray.cs @@ -1,13 +1,12 @@ #pragma warning disable CS0168 // Variable is declared but never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_06; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages; - #endregion INCLUDE - } - } -} + #region INCLUDE + string[] languages; + #endregion INCLUDE + } + } diff --git a/src/Chapter03/Listing03.07.DeclaringATwoDimensionalArray.cs b/src/Chapter03/Listing03.07.DeclaringATwoDimensionalArray.cs index 91ee312ac..9aa6a79e8 100644 --- a/src/Chapter03/Listing03.07.DeclaringATwoDimensionalArray.cs +++ b/src/Chapter03/Listing03.07.DeclaringATwoDimensionalArray.cs @@ -1,18 +1,17 @@ #pragma warning disable CS0168 // Variable is declared but never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_07; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - // | | - // ---+---+--- - // | | - // ---+---+--- - // | | - int[,] cells; - #endregion INCLUDE - } + #region INCLUDE + // | | + // ---+---+--- + // | | + // ---+---+--- + // | | + int[,] cells; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.08.ArrayDeclarationWithAssignment.cs b/src/Chapter03/Listing03.08.ArrayDeclarationWithAssignment.cs index 4ce6750eb..d3f39e0b5 100644 --- a/src/Chapter03/Listing03.08.ArrayDeclarationWithAssignment.cs +++ b/src/Chapter03/Listing03.08.ArrayDeclarationWithAssignment.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_08; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = { "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript" }; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = { "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript" }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.09.ArrayAssignmentFollowingDeclaration.cs b/src/Chapter03/Listing03.09.ArrayAssignmentFollowingDeclaration.cs index 5942f4e41..f9f219804 100644 --- a/src/Chapter03/Listing03.09.ArrayAssignmentFollowingDeclaration.cs +++ b/src/Chapter03/Listing03.09.ArrayAssignmentFollowingDeclaration.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_09; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages; - languages = new string[]{ "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript" }; - #endregion INCLUDE - } + #region INCLUDE + string[] languages; + languages = new string[]{ "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript" }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.10.ArrayAssignmentWithNewDuringDeclaration.cs b/src/Chapter03/Listing03.10.ArrayAssignmentWithNewDuringDeclaration.cs index 1750dad55..f426c61b5 100644 --- a/src/Chapter03/Listing03.10.ArrayAssignmentWithNewDuringDeclaration.cs +++ b/src/Chapter03/Listing03.10.ArrayAssignmentWithNewDuringDeclaration.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_10; + +public class Program { - public class Program - { - public static void Main() - { - #region INCLUDE - string[] languages = new string[]{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript" }; - #endregion INCLUDE - } + public static void Main() + { + #region INCLUDE + string[] languages = new string[]{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript" }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.11.DeclarationAndAssignmentWithTheNewKeyword.cs b/src/Chapter03/Listing03.11.DeclarationAndAssignmentWithTheNewKeyword.cs index 433e42472..c3ebbf73a 100644 --- a/src/Chapter03/Listing03.11.DeclarationAndAssignmentWithTheNewKeyword.cs +++ b/src/Chapter03/Listing03.11.DeclarationAndAssignmentWithTheNewKeyword.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_11; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new string[9]{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript" }; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new string[9]{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript" }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.12.AssigningWithoutLiteralValues.cs b/src/Chapter03/Listing03.12.AssigningWithoutLiteralValues.cs index 29e3f0a60..a45f2a13c 100644 --- a/src/Chapter03/Listing03.12.AssigningWithoutLiteralValues.cs +++ b/src/Chapter03/Listing03.12.AssigningWithoutLiteralValues.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_12; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new string[9]; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new string[9]; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.13.DefiningTheArraySizeAtRuntime.cs b/src/Chapter03/Listing03.13.DefiningTheArraySizeAtRuntime.cs index 3dce491b8..069a1e39c 100644 --- a/src/Chapter03/Listing03.13.DefiningTheArraySizeAtRuntime.cs +++ b/src/Chapter03/Listing03.13.DefiningTheArraySizeAtRuntime.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_13; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] groceryList; - Console.Write("How many items on the list? "); - int size = int.Parse(Console.ReadLine()); - groceryList = new string[size]; - // ... - #endregion INCLUDE - } + #region INCLUDE + string[] groceryList; + Console.Write("How many items on the list? "); + int size = int.Parse(Console.ReadLine()); + groceryList = new string[size]; + // ... + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.14.DeclaringATwoDimensionalArray.cs b/src/Chapter03/Listing03.14.DeclaringATwoDimensionalArray.cs index 6cca378a7..e10d52fd6 100644 --- a/src/Chapter03/Listing03.14.DeclaringATwoDimensionalArray.cs +++ b/src/Chapter03/Listing03.14.DeclaringATwoDimensionalArray.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_14; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int[,] cells = new int[3,3]; - #endregion INCLUDE - } + #region INCLUDE + int[,] cells = new int[3,3]; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.15.InitializingATwoDimensionalArrayOfIntegers.cs b/src/Chapter03/Listing03.15.InitializingATwoDimensionalArrayOfIntegers.cs index 8d67999ad..55f804036 100644 --- a/src/Chapter03/Listing03.15.InitializingATwoDimensionalArrayOfIntegers.cs +++ b/src/Chapter03/Listing03.15.InitializingATwoDimensionalArrayOfIntegers.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_15; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int[,] cells = { - {1, 0, 2}, - {1, 2, 0}, - {1, 2, 1} - }; - #endregion INCLUDE - } + #region INCLUDE + int[,] cells = { + {1, 0, 2}, + {1, 2, 0}, + {1, 2, 1} + }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.16.AMultidimensionalArrayWithInconsistentSizeCausingAnError.cs b/src/Chapter03/Listing03.16.AMultidimensionalArrayWithInconsistentSizeCausingAnError.cs index c25bdad9d..cb65ba13d 100644 --- a/src/Chapter03/Listing03.16.AMultidimensionalArrayWithInconsistentSizeCausingAnError.cs +++ b/src/Chapter03/Listing03.16.AMultidimensionalArrayWithInconsistentSizeCausingAnError.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_16; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - // ERROR: Each dimension must be consistently sized - #region EXCLUDE - /* - #endregion EXLUDE - int[,] cells = { - {1, 0, 2, 0}, - {1, 2, 0}, - {1, 2}, - {1} - }; - #region EXCLUDE - */ - #endregion EXCLUDE - #endregion INCLUDE - } + #region INCLUDE + // ERROR: Each dimension must be consistently sized + #region EXCLUDE + /* + #endregion EXLUDE + int[,] cells = { + {1, 0, 2, 0}, + {1, 2, 0}, + {1, 2}, + {1} + }; + #region EXCLUDE + */ + #endregion EXCLUDE + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.17.InitializingAThreeDimensionalArray.cs b/src/Chapter03/Listing03.17.InitializingAThreeDimensionalArray.cs index 28985bd63..88f0bd33d 100644 --- a/src/Chapter03/Listing03.17.InitializingAThreeDimensionalArray.cs +++ b/src/Chapter03/Listing03.17.InitializingAThreeDimensionalArray.cs @@ -1,37 +1,36 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_17; + +public class Program { - public class Program + public static void Main() { - public static void Main() + #region INCLUDE + bool[, ,] cells; + cells = new bool[2, 3, 3] { - #region INCLUDE - bool[, ,] cells; - cells = new bool[2, 3, 3] + // Player 1 moves + // X | | + // ---+---+--- + // X | | + // ---+---+--- + // X | | X { - // Player 1 moves - // X | | - // ---+---+--- - // X | | - // ---+---+--- - // X | | X - { - {true, false, false}, - {true, false, false}, - {true, false, true} - }, - // Player 2 moves - // | | O - // ---+---+--- - // | O | - // ---+---+--- - // | O | - { - {false, false, true}, - {false, true, false}, - {false, true, true} - } - }; - #endregion INCLUDE - } + {true, false, false}, + {true, false, false}, + {true, false, true} + }, + // Player 2 moves + // | | O + // ---+---+--- + // | O | + // ---+---+--- + // | O | + { + {false, false, true}, + {false, true, false}, + {false, true, true} + } + }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.18.InitializingAJaggedArray.cs b/src/Chapter03/Listing03.18.InitializingAJaggedArray.cs index 6b572898e..4f4f547d5 100644 --- a/src/Chapter03/Listing03.18.InitializingAJaggedArray.cs +++ b/src/Chapter03/Listing03.18.InitializingAJaggedArray.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_18; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int[][] cells = { - new [] {1, 0, 2, 0}, - new [] {1, 2, 0}, - new [] {1, 2}, - new [] {1} - }; - #endregion INCLUDE - } + #region INCLUDE + int[][] cells = { + new [] {1, 0, 2, 0}, + new [] {1, 2, 0}, + new [] {1, 2}, + new [] {1} + }; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.19.DeclaringAndAccessingAnArray.cs b/src/Chapter03/Listing03.19.DeclaringAndAccessingAnArray.cs index c8c843a84..b2364d9bb 100644 --- a/src/Chapter03/Listing03.19.DeclaringAndAccessingAnArray.cs +++ b/src/Chapter03/Listing03.19.DeclaringAndAccessingAnArray.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_19; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new []{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript"}; - // Retrieve fifth item in languages array (TypeScript) - string language = languages[4]; - // Write "TypeScript" - Console.WriteLine(language); - // Retrieve second item from the end (Python) - language = languages[^3]; - // Write "Python" - Console.WriteLine(language); - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new []{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript"}; + // Retrieve fifth item in languages array (TypeScript) + string language = languages[4]; + // Write "TypeScript" + Console.WriteLine(language); + // Retrieve second item from the end (Python) + language = languages[^3]; + // Write "Python" + Console.WriteLine(language); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.20.SwappingDataBetweenPositionsInAnArray.cs b/src/Chapter03/Listing03.20.SwappingDataBetweenPositionsInAnArray.cs index c7ca21401..3733d7fb3 100644 --- a/src/Chapter03/Listing03.20.SwappingDataBetweenPositionsInAnArray.cs +++ b/src/Chapter03/Listing03.20.SwappingDataBetweenPositionsInAnArray.cs @@ -1,21 +1,20 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_20; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new [] { - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript" }; - // Save "C++" to variable called language - string language = languages[3]; - // Assign "Java" to the C++ position - languages[3] = languages[2]; - // Assign language to location of "Java" - languages[2] = language; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new [] { + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript" }; + // Save "C++" to variable called language + string language = languages[3]; + // Assign "Java" to the C++ position + languages[3] = languages[2]; + // Assign language to location of "Java" + languages[2] = language; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.21.InitializingATwoDimensionalArrayOfIntegers.cs b/src/Chapter03/Listing03.21.InitializingATwoDimensionalArrayOfIntegers.cs index a637d7f24..0e8ea5459 100644 --- a/src/Chapter03/Listing03.21.InitializingATwoDimensionalArrayOfIntegers.cs +++ b/src/Chapter03/Listing03.21.InitializingATwoDimensionalArrayOfIntegers.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_21; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int[,] cells = { - {1, 0, 2}, - {0, 2, 0}, - {1, 2, 1} - }; - // Set the winning tic-tac-toe move to be player 1 - cells[1, 0] = 1; - #endregion INCLUDE - } + #region INCLUDE + int[,] cells = { + {1, 0, 2}, + {0, 2, 0}, + {1, 2, 1} + }; + // Set the winning tic-tac-toe move to be player 1 + cells[1, 0] = 1; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.22.DeclaringAJaggedArray.cs b/src/Chapter03/Listing03.22.DeclaringAJaggedArray.cs index 779d9c176..1c80b2b72 100644 --- a/src/Chapter03/Listing03.22.DeclaringAJaggedArray.cs +++ b/src/Chapter03/Listing03.22.DeclaringAJaggedArray.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_22; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int[][] cells = { - new []{1, 0, 2}, - new []{0, 2, 0}, - new []{1, 2, 1} - }; + #region INCLUDE + int[][] cells = { + new []{1, 0, 2}, + new []{0, 2, 0}, + new []{1, 2, 1} + }; - cells[1][0] = 1; - // ... - #endregion INCLUDE - } + cells[1][0] = 1; + // ... + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.23.RetrievingTheLengthOfAnArray.cs b/src/Chapter03/Listing03.23.RetrievingTheLengthOfAnArray.cs index fa0ecc56f..6d2c4c938 100644 --- a/src/Chapter03/Listing03.23.RetrievingTheLengthOfAnArray.cs +++ b/src/Chapter03/Listing03.23.RetrievingTheLengthOfAnArray.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_23; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - string[] languages = new string[9]; - // ... - #region INCLUDE - Console.WriteLine( - $"There are {languages.Length} languages in the array."); - #endregion INCLUDE - } + string[] languages = new string[9]; + // ... + #region INCLUDE + Console.WriteLine( + $"There are {languages.Length} languages in the array."); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.24.AccessingOutsideTheBoundsOfAnArrayThrowingAnException.cs b/src/Chapter03/Listing03.24.AccessingOutsideTheBoundsOfAnArrayThrowingAnException.cs index 0197af795..747f12980 100644 --- a/src/Chapter03/Listing03.24.AccessingOutsideTheBoundsOfAnArrayThrowingAnException.cs +++ b/src/Chapter03/Listing03.24.AccessingOutsideTheBoundsOfAnArrayThrowingAnException.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_24 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_24; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new string[9]; - // ... - // RUNTIME ERROR: index out of bounds - should - // be 8 for the last element - languages[4] = languages[9]; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new string[9]; + // ... + // RUNTIME ERROR: index out of bounds - should + // be 8 for the last element + languages[4] = languages[9]; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.25.UsingLengthMinus1InTheArrayIndex.cs b/src/Chapter03/Listing03.25.UsingLengthMinus1InTheArrayIndex.cs index 08b5599b6..6d5ae0aef 100644 --- a/src/Chapter03/Listing03.25.UsingLengthMinus1InTheArrayIndex.cs +++ b/src/Chapter03/Listing03.25.UsingLengthMinus1InTheArrayIndex.cs @@ -1,16 +1,15 @@ // Justification: Demonstrating how to use the length to index the last item in the array. #pragma warning disable IDE0056 // Use index operator -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_25 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_25; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new string[9]; - // ... - languages[4] = languages[languages.Length - 1]; - #endregion INCLUDE - } + #region INCLUDE + string[] languages = new string[9]; + // ... + languages[4] = languages[languages.Length - 1]; + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.26.Slicing.cs b/src/Chapter03/Listing03.26.Slicing.cs index 69c456f5e..d218160d1 100644 --- a/src/Chapter03/Listing03.26.Slicing.cs +++ b/src/Chapter03/Listing03.26.Slicing.cs @@ -1,39 +1,38 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_26 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_26; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new [] { - "C#", "COBOL", "Java", - "C++", "TypeScript", "Swift", - "Python", "Lisp", "JavaScript"}; + #region INCLUDE + string[] languages = new [] { + "C#", "COBOL", "Java", + "C++", "TypeScript", "Swift", + "Python", "Lisp", "JavaScript"}; - Console.WriteLine($@" 0..3: { - string.Join(", ", languages[0..3]) // C#, COBOL, Java - }"); - Console.WriteLine($@"^3..^0: { - string.Join(", ", languages[^3..^0]) // Python, Lisp, JavaScript - }"); - Console.WriteLine($@" 3..^3: { - string.Join(", ", languages[3..^3]) // C++, TypeScript, Swift - }"); - Console.WriteLine($@" ..^6: { - string.Join(", ", languages[..^6]) // C#, COBOL, Java - }"); - Console.WriteLine($@" 6..: { - string.Join(", ", languages[6..]) // Python, Lisp, JavaScript - }"); - Console.WriteLine($@" ..: { - // C#, COBOL, Java, C++, TypeScript, Swift, Python, Lisp, JavaScript - string.Join(", ", languages[..]) // Python, Lisp, JavaScript - }"); - Console.WriteLine($@" ..: { - // C#, COBOL, Java, C++, TypeScript, Swift, Python, Lisp, JavaScript - string.Join(", ", languages[0..^0]) // Python, Lisp, JavaScript - }"); - #endregion INCLUDE - } + Console.WriteLine($@" 0..3: { + string.Join(", ", languages[0..3]) // C#, COBOL, Java + }"); + Console.WriteLine($@"^3..^0: { + string.Join(", ", languages[^3..^0]) // Python, Lisp, JavaScript + }"); + Console.WriteLine($@" 3..^3: { + string.Join(", ", languages[3..^3]) // C++, TypeScript, Swift + }"); + Console.WriteLine($@" ..^6: { + string.Join(", ", languages[..^6]) // C#, COBOL, Java + }"); + Console.WriteLine($@" 6..: { + string.Join(", ", languages[6..]) // Python, Lisp, JavaScript + }"); + Console.WriteLine($@" ..: { + // C#, COBOL, Java, C++, TypeScript, Swift, Python, Lisp, JavaScript + string.Join(", ", languages[..]) // Python, Lisp, JavaScript + }"); + Console.WriteLine($@" ..: { + // C#, COBOL, Java, C++, TypeScript, Swift, Python, Lisp, JavaScript + string.Join(", ", languages[0..^0]) // Python, Lisp, JavaScript + }"); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.27.AdditionalArrayMethods.cs b/src/Chapter03/Listing03.27.AdditionalArrayMethods.cs index b3a848437..e89785cba 100644 --- a/src/Chapter03/Listing03.27.AdditionalArrayMethods.cs +++ b/src/Chapter03/Listing03.27.AdditionalArrayMethods.cs @@ -1,51 +1,50 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_27 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_27; + +public class ProgrammingLanguages { - public class ProgrammingLanguages + public static void Main() { - public static void Main() - { - #region INCLUDE - string[] languages = new string[]{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Swift", - "Python", "Lisp", "JavaScript"}; + #region INCLUDE + string[] languages = new string[]{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Swift", + "Python", "Lisp", "JavaScript"}; - #region HIGHLIGHT - Array.Sort(languages); - #endregion HIGHLIGHT + #region HIGHLIGHT + Array.Sort(languages); + #endregion HIGHLIGHT - string searchString = "COBOL"; - #region HIGHLIGHT - int index = Array.BinarySearch( - languages, searchString); - #endregion HIGHLIGHT - Console.WriteLine( - "The wave of the future, " - + $"{ searchString }, is at index { index }."); + string searchString = "COBOL"; + #region HIGHLIGHT + int index = Array.BinarySearch( + languages, searchString); + #endregion HIGHLIGHT + Console.WriteLine( + "The wave of the future, " + + $"{ searchString }, is at index { index }."); - Console.WriteLine(); - Console.WriteLine( - $"{ "First Element",-20 }\t{ "Last Element",-20 }"); - Console.WriteLine( - $"{ "-------------",-20 }\t{ "------------",-20 }"); - Console.WriteLine( - $"{ languages[0],-20 }\t{ languages[^1],-20 }"); - #region HIGHLIGHT - Array.Reverse(languages); - #endregion HIGHLIGHT - Console.WriteLine( - $"{ languages[0],-20 }\t{ languages[^1],-20 }"); - // Note this does not remove all items from the array - // Rather it sets each item to the type's default value - #region HIGHLIGHT - Array.Clear(languages, 0, languages.Length); - #endregion HIGHLIGHT - Console.WriteLine( - $"{ languages[0],-20 }\t{ languages[^1],-20 }"); - Console.WriteLine( - $"After clearing, the array size is: { languages.Length }"); - #endregion INCLUDE - } + Console.WriteLine(); + Console.WriteLine( + $"{ "First Element",-20 }\t{ "Last Element",-20 }"); + Console.WriteLine( + $"{ "-------------",-20 }\t{ "------------",-20 }"); + Console.WriteLine( + $"{ languages[0],-20 }\t{ languages[^1],-20 }"); + #region HIGHLIGHT + Array.Reverse(languages); + #endregion HIGHLIGHT + Console.WriteLine( + $"{ languages[0],-20 }\t{ languages[^1],-20 }"); + // Note this does not remove all items from the array + // Rather it sets each item to the type's default value + #region HIGHLIGHT + Array.Clear(languages, 0, languages.Length); + #endregion HIGHLIGHT + Console.WriteLine( + $"{ languages[0],-20 }\t{ languages[^1],-20 }"); + Console.WriteLine( + $"After clearing, the array size is: { languages.Length }"); + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.28.RetrievingAParticularDimensionsSize.cs b/src/Chapter03/Listing03.28.RetrievingAParticularDimensionsSize.cs index 6d587c242..a56f5f1e2 100644 --- a/src/Chapter03/Listing03.28.RetrievingAParticularDimensionsSize.cs +++ b/src/Chapter03/Listing03.28.RetrievingAParticularDimensionsSize.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_28 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_28; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - bool[, ,] cells; - cells = new bool[2, 3, 3]; - Console.WriteLine(cells.GetLength(0)); // Displays 2 - Console.WriteLine(cells.Rank); // Displays 3 - #endregion INCLUDE - } + #region INCLUDE + bool[, ,] cells; + cells = new bool[2, 3, 3]; + Console.WriteLine(cells.GetLength(0)); // Displays 2 + Console.WriteLine(cells.Rank); // Displays 3 + #endregion INCLUDE } } diff --git a/src/Chapter03/Listing03.29.LookingForCommandlineOptions.cs b/src/Chapter03/Listing03.29.LookingForCommandlineOptions.cs index 05e81f3fe..7f1ed6f31 100644 --- a/src/Chapter03/Listing03.29.LookingForCommandlineOptions.cs +++ b/src/Chapter03/Listing03.29.LookingForCommandlineOptions.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_29 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_29; + +public class Program { - public class Program + #region INCLUDE + public static void Main(string[] args) { - #region INCLUDE - public static void Main(string[] args) + // ... + if(args[0][0] == '-') { - // ... - if(args[0][0] == '-') - { - // This parameter is an option - } + // This parameter is an option } - #endregion INCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter03/Listing03.30.LookingForCommandlineOptionsSimplified.cs b/src/Chapter03/Listing03.30.LookingForCommandlineOptionsSimplified.cs index 6cb3a73ca..d890a9c0f 100644 --- a/src/Chapter03/Listing03.30.LookingForCommandlineOptionsSimplified.cs +++ b/src/Chapter03/Listing03.30.LookingForCommandlineOptionsSimplified.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_30 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_30; + +public class Program { - public class Program + #region INCLUDE + public static void Main(string[] args) { - #region INCLUDE - public static void Main(string[] args) + // ... + string arg = args[0]; + if(arg[0] == '-') { - // ... - string arg = args[0]; - if(arg[0] == '-') - { - // This parameter is an option - } + // This parameter is an option } - #endregion INCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter03/Listing03.31.ReversingAString.cs b/src/Chapter03/Listing03.31.ReversingAString.cs index ceb4c2ffd..1e5f6873c 100644 --- a/src/Chapter03/Listing03.31.ReversingAString.cs +++ b/src/Chapter03/Listing03.31.ReversingAString.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_31 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_31; + +public class Palindrome { - public class Palindrome + public static void Main() { - public static void Main() - { - #region INCLUDE - string reverse, palindrome; - char[] temp; + #region INCLUDE + string reverse, palindrome; + char[] temp; - Console.Write("Enter a palindrome: "); - palindrome = Console.ReadLine(); + Console.Write("Enter a palindrome: "); + palindrome = Console.ReadLine(); - // Remove spaces and convert to lowercase - reverse = palindrome.Replace(" ", ""); - reverse = reverse.ToLower(); + // Remove spaces and convert to lowercase + reverse = palindrome.Replace(" ", ""); + reverse = reverse.ToLower(); - #region HIGHLIGHT - // Convert to an array - temp = reverse.ToCharArray(); - #endregion HIGHLIGHT + #region HIGHLIGHT + // Convert to an array + temp = reverse.ToCharArray(); + #endregion HIGHLIGHT - #region HIGHLIGHT - // Reverse the array - Array.Reverse(temp); - #endregion HIGHLIGHT + #region HIGHLIGHT + // Reverse the array + Array.Reverse(temp); + #endregion HIGHLIGHT - // Convert the array back to a string and - // check if reverse string is the same - if (reverse == new string(temp)) - { - Console.WriteLine( - $"\"{palindrome}\" is a palindrome."); - } - else - { - Console.WriteLine( - $"\"{palindrome}\" is NOT a palindrome."); - } - #endregion INCLUDE + // Convert the array back to a string and + // check if reverse string is the same + if (reverse == new string(temp)) + { + Console.WriteLine( + $"\"{palindrome}\" is a palindrome."); + } + else + { + Console.WriteLine( + $"\"{palindrome}\" is NOT a palindrome."); } + #endregion INCLUDE } } diff --git a/src/Chapter03/Table03.01.TupleDeclarationAndAssignment.cs b/src/Chapter03/Table03.01.TupleDeclarationAndAssignment.cs index 5a7b9af2b..0cb87b02a 100644 --- a/src/Chapter03/Table03.01.TupleDeclarationAndAssignment.cs +++ b/src/Chapter03/Table03.01.TupleDeclarationAndAssignment.cs @@ -1,119 +1,118 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Table03_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Table03_01; + +public class TupleDeclarationAndAssigment { - public class TupleDeclarationAndAssigment + // 1. + public void AssignTupleToIndividuallyDeclaredVaraibles() { - // 1. - public void AssignTupleToIndividuallyDeclaredVaraibles() - { - (string country, string capital, double gdpPerCapita) = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - country}, {capital}: {gdpPerCapita}"); - } + (string country, string capital, double gdpPerCapita) = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + country}, {capital}: {gdpPerCapita}"); + } - // 2. - public void AssignTupleToIndividuallyDeclaredVariablesThatArPreDeclared() - { - string country; - string capital; - double gdpPerCapita; + // 2. + public void AssignTupleToIndividuallyDeclaredVariablesThatArPreDeclared() + { + string country; + string capital; + double gdpPerCapita; - (country, capital, gdpPerCapita) = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - country}, {capital}: {gdpPerCapita}"); - } + (country, capital, gdpPerCapita) = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + country}, {capital}: {gdpPerCapita}"); + } - // 3. - public void AssignTupleToIndividuallyDeclaredAndImplicitlyTypedVariables() - { - (var country, var capital, var gdpPerCapita) = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - country}, {capital}: {gdpPerCapita}"); - } + // 3. + public void AssignTupleToIndividuallyDeclaredAndImplicitlyTypedVariables() + { + (var country, var capital, var gdpPerCapita) = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + country}, {capital}: {gdpPerCapita}"); + } - // 4. - public void AssignTupleToIndividuallyDeclaredVariablesThatImplicitlyTypedWithADistributiveSyntax() - { - var (country, capital, gdpPerCapita) = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - country}, {capital}: {gdpPerCapita}"); - } + // 4. + public void AssignTupleToIndividuallyDeclaredVariablesThatImplicitlyTypedWithADistributiveSyntax() + { + var (country, capital, gdpPerCapita) = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + country}, {capital}: {gdpPerCapita}"); + } - // 5. - public void DeclareANamedItemTupleAndAssignItTupleValuesAndThenAccessTheTupleItemsByName() - { - (string Name, string Capital, double GdpPerCapita) countryInfo = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - countryInfo.Name}, {countryInfo.Capital}: { - countryInfo.GdpPerCapita}"); - } + // 5. + public void DeclareANamedItemTupleAndAssignItTupleValuesAndThenAccessTheTupleItemsByName() + { + (string Name, string Capital, double GdpPerCapita) countryInfo = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + countryInfo.Name}, {countryInfo.Capital}: { + countryInfo.GdpPerCapita}"); + } - // 6. - public void AssignANamedItemTupleToASingleImplicitlyTypedVariableThatIsImplicitlyTypedAndThenAccessTheTupleItemsByName() - { - var countryInfo = - (Name: "Burundi", Capital: "Bujumbura", GdpPerCapita: 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - countryInfo.Name}, {countryInfo.Capital}: { - countryInfo.GdpPerCapita}"); + // 6. + public void AssignANamedItemTupleToASingleImplicitlyTypedVariableThatIsImplicitlyTypedAndThenAccessTheTupleItemsByName() + { + var countryInfo = + (Name: "Burundi", Capital: "Bujumbura", GdpPerCapita: 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + countryInfo.Name}, {countryInfo.Capital}: { + countryInfo.GdpPerCapita}"); - } + } - // 7. - public void AssignAnUnnamedTupleToASingleImplicitlyTypedVariableAndThenAccessTheTupleElementsByTheirItemNumberProperty() - { - var countryInfo = - ("Burundi", "Bujumbura", 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - countryInfo.Item1}, {countryInfo.Item2}: { - countryInfo.Item3}"); - } + // 7. + public void AssignAnUnnamedTupleToASingleImplicitlyTypedVariableAndThenAccessTheTupleElementsByTheirItemNumberProperty() + { + var countryInfo = + ("Burundi", "Bujumbura", 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + countryInfo.Item1}, {countryInfo.Item2}: { + countryInfo.Item3}"); + } - // 8. + // 8. // Justification: Demonstrating the fact that the name is an alias to ItemX. #pragma warning disable IDE0033 // Use explicitly provided tuple name - public void AssignANamedItemTupleToASingleImplicitlyTypedVariableAndThenAccessTheTupleItemsByTheirItemNumberProperty() - { - var countryInfo = - (Name: "Burundi", Capital: "Bujumbura", GdpPerCapita: 263.67); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - countryInfo.Item1}, {countryInfo.Item2}: { - countryInfo.Item3}"); - } + public void AssignANamedItemTupleToASingleImplicitlyTypedVariableAndThenAccessTheTupleItemsByTheirItemNumberProperty() + { + var countryInfo = + (Name: "Burundi", Capital: "Bujumbura", GdpPerCapita: 263.67); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + countryInfo.Item1}, {countryInfo.Item2}: { + countryInfo.Item3}"); + } #pragma warning restore IDE0033 // Use explicitly provided tuple name - // 9. - public void DiscardPortionsOfTheTupleWithUnderscores() - { - (string name, _, double gdpPerCapita) = - ("Burundi", "Bujumbura", 263.67); - } + // 9. + public void DiscardPortionsOfTheTupleWithUnderscores() + { + (string name, _, double gdpPerCapita) = + ("Burundi", "Bujumbura", 263.67); + } - // 10. - public void TupleElementNamesCanBeInferredFromVariableAndPropertyNames() - { - string country = "Burundi"; - string capital = "Bujumbura"; - double gdpPerCapita = 263.67; + // 10. + public void TupleElementNamesCanBeInferredFromVariableAndPropertyNames() + { + string country = "Burundi"; + string capital = "Bujumbura"; + double gdpPerCapita = 263.67; - var countryInfo = - (country, capital, gdpPerCapita); - Console.WriteLine( - $@"The poorest country in the world in 2017 was { - countryInfo.country}, {countryInfo.capital}: { - countryInfo.gdpPerCapita}"); - } + var countryInfo = + (country, capital, gdpPerCapita); + Console.WriteLine( + $@"The poorest country in the world in 2017 was { + countryInfo.country}, {countryInfo.capital}: { + countryInfo.gdpPerCapita}"); } } diff --git a/src/Chapter03/Table03.02.ArrayHighlights.cs b/src/Chapter03/Table03.02.ArrayHighlights.cs index bbb5d17dd..ed570eed8 100644 --- a/src/Chapter03/Table03.02.ArrayHighlights.cs +++ b/src/Chapter03/Table03.02.ArrayHighlights.cs @@ -1,79 +1,78 @@ // Justification: Only snippets of source code shown for elucidation. #pragma warning disable CS0168 // Variable is declared but never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Table03_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Table03_02; + +public class ArrayHighlights { - public class ArrayHighlights + // 1. + static public void Declaration() { - // 1. - static public void Declaration() - { - string[] languages; // one-dimensional - int[,] cells; // two-dimensional - } + string[] languages; // one-dimensional + int[,] cells; // two-dimensional + } - // 2. - static public void Assignment() - { - string[] languages = { - "C#", "COBOL", "Java", - "C++", "TypeScript", "Pascal", - "Python", "Lisp", "JavaScript"}; - languages = new string[]{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Pascal", - "Python", "Lisp", "JavaScript" }; - // Multidimensional array assignment - // and initialization - int[,] cells = new [,] { - { 1, 0, 2}, - { 1, 2, 0}, - { 1, 2, 1} - }; - languages = new string[9]; - } + // 2. + static public void Assignment() + { + string[] languages = { + "C#", "COBOL", "Java", + "C++", "TypeScript", "Pascal", + "Python", "Lisp", "JavaScript"}; + languages = new string[]{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Pascal", + "Python", "Lisp", "JavaScript" }; + // Multidimensional array assignment + // and initialization + int[,] cells = new [,] { + { 1, 0, 2}, + { 1, 2, 0}, + { 1, 2, 1} + }; + languages = new string[9]; + } - // 3. - static public void ForwardAndReverseAccessingAnArray() - { - string[] languages = new []{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript"}; - // Retrieve fifth item in languages array (TypeScript) - string language = languages[4]; - // Write “TypeScript” - Console.WriteLine(language); - // Retrieve second item from the end (Python) - language = languages[^3]; - // Write “Python” - Console.WriteLine(language); - } + // 3. + static public void ForwardAndReverseAccessingAnArray() + { + string[] languages = new []{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript"}; + // Retrieve fifth item in languages array (TypeScript) + string language = languages[4]; + // Write “TypeScript” + Console.WriteLine(language); + // Retrieve second item from the end (Python) + language = languages[^3]; + // Write “Python” + Console.WriteLine(language); + } - // 4. - static public void Ranges() - { - string[] languages = new []{ - "C#", "COBOL", "Java", - "C++", "TypeScript", "Visual Basic", - "Python", "Lisp", "JavaScript"}; + // 4. + static public void Ranges() + { + string[] languages = new []{ + "C#", "COBOL", "Java", + "C++", "TypeScript", "Visual Basic", + "Python", "Lisp", "JavaScript"}; - Console.WriteLine($@"^3..^0: { - // Python, Lisp, JavaScript - string.Join(", ", languages[^3..^0]) - }"); - Console.WriteLine($@"^3..: { - // Python, Lisp, JavaScript - string.Join(", ", languages[^3..]) - }"); - Console.WriteLine($@" 3..^3: { - // C++, TypeScript, Visual Basic - string.Join(", ", languages[3..^3]) - }"); - Console.WriteLine($@" ..^6: { - // C#, COBOL, Java - string.Join(", ", languages[..^6]) - }"); - } + Console.WriteLine($@"^3..^0: { + // Python, Lisp, JavaScript + string.Join(", ", languages[^3..^0]) + }"); + Console.WriteLine($@"^3..: { + // Python, Lisp, JavaScript + string.Join(", ", languages[^3..]) + }"); + Console.WriteLine($@" 3..^3: { + // C++, TypeScript, Visual Basic + string.Join(", ", languages[3..^3]) + }"); + Console.WriteLine($@" ..^6: { + // C#, COBOL, Java + string.Join(", ", languages[..^6]) + }"); } } diff --git a/src/Chapter04/Listing04.01.SimpleOperator.cs b/src/Chapter04/Listing04.01.SimpleOperator.cs index f721f611c..da7b6bd6c 100644 --- a/src/Chapter04/Listing04.01.SimpleOperator.cs +++ b/src/Chapter04/Listing04.01.SimpleOperator.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_01; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int difference = 4 - 2; - #endregion INCLUDE - Console.WriteLine(difference); - } + #region INCLUDE + int difference = 4 - 2; + #endregion INCLUDE + Console.WriteLine(difference); } } diff --git a/src/Chapter04/Listing04.02.Negative.cs b/src/Chapter04/Listing04.02.Negative.cs index 4538da76e..a034c1ab2 100644 --- a/src/Chapter04/Listing04.02.Negative.cs +++ b/src/Chapter04/Listing04.02.Negative.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_02; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - // World Debt on 2022-11-06 - // see https://worlddebtclocks.com/ - decimal debt = -72748555131730M; - #endregion INCLUDE + #region INCLUDE + // World Debt on 2022-11-06 + // see https://worlddebtclocks.com/ + decimal debt = -72748555131730M; + #endregion INCLUDE - Console.WriteLine(debt); - } + Console.WriteLine(debt); } } diff --git a/src/Chapter04/Listing04.03.BinaryOperators.cs b/src/Chapter04/Listing04.03.BinaryOperators.cs index 9f7375ae8..a4c560245 100644 --- a/src/Chapter04/Listing04.03.BinaryOperators.cs +++ b/src/Chapter04/Listing04.03.BinaryOperators.cs @@ -1,32 +1,31 @@ // Justification: Checking for null isn't discussed yet. #pragma warning disable CS8604 // Possible null reference argument -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_03; + +public class Division { - public class Division + public static void Main() { - public static void Main() - { - #region INCLUDE - int numerator; - int denominator; - int quotient; - int remainder; + #region INCLUDE + int numerator; + int denominator; + int quotient; + int remainder; - Console.Write("Enter the numerator: "); - numerator = int.Parse(Console.ReadLine()); + Console.Write("Enter the numerator: "); + numerator = int.Parse(Console.ReadLine()); - Console.Write("Enter the denominator: "); - denominator = int.Parse(Console.ReadLine()); + Console.Write("Enter the denominator: "); + denominator = int.Parse(Console.ReadLine()); - #region HIGHLIGHT - quotient = numerator / denominator; - remainder = numerator % denominator; - #endregion HIGHLIGHT + #region HIGHLIGHT + quotient = numerator / denominator; + remainder = numerator % denominator; + #endregion HIGHLIGHT - Console.WriteLine( - $"{numerator} / {denominator} = { - quotient} with remainder {remainder}"); - #endregion INCLUDE - } + Console.WriteLine( + $"{numerator} / {denominator} = { + quotient} with remainder {remainder}"); + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter04/Listing04.04.NonNumericTypes.cs b/src/Chapter04/Listing04.04.NonNumericTypes.cs index e109b2869..d0cf852f9 100644 --- a/src/Chapter04/Listing04.04.NonNumericTypes.cs +++ b/src/Chapter04/Listing04.04.NonNumericTypes.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_04; + +#region INCLUDE +public class FortyTwo { - #region INCLUDE - public class FortyTwo + public static void Main() { - public static void Main() - { - short windSpeed = 42; - Console.WriteLine( - $"The original Tacoma Bridge in Washington" + - $"{Environment.NewLine}was " - + "brought down by a " - + windSpeed + " mile/hour wind."); - } + short windSpeed = 42; + Console.WriteLine( + $"The original Tacoma Bridge in Washington" + + $"{Environment.NewLine}was " + + "brought down by a " + + windSpeed + " mile/hour wind."); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter04/Listing04.05.CharConcatenation.cs b/src/Chapter04/Listing04.05.CharConcatenation.cs index 4b282662b..8770564b3 100644 --- a/src/Chapter04/Listing04.05.CharConcatenation.cs +++ b/src/Chapter04/Listing04.05.CharConcatenation.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_05; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int n = '3' + '4'; - char c = (char)n; - Console.WriteLine(c); // Writes out g - #endregion INCLUDE - } + #region INCLUDE + int n = '3' + '4'; + char c = (char)n; + Console.WriteLine(c); // Writes out g + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.06.CharDifferences.cs b/src/Chapter04/Listing04.06.CharDifferences.cs index 3f588116c..a91e64822 100644 --- a/src/Chapter04/Listing04.06.CharDifferences.cs +++ b/src/Chapter04/Listing04.06.CharDifferences.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_06; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int distance = 'f' - 'c'; - Console.WriteLine(distance); - #endregion INCLUDE - } + #region INCLUDE + int distance = 'f' - 'c'; + Console.WriteLine(distance); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.07.UnexpectedInequality.cs b/src/Chapter04/Listing04.07.UnexpectedInequality.cs index c791561e2..285de6f27 100644 --- a/src/Chapter04/Listing04.07.UnexpectedInequality.cs +++ b/src/Chapter04/Listing04.07.UnexpectedInequality.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_07; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - decimal decimalNumber = 4.2M; - double doubleNumber1 = 0.1F * 42F; - double doubleNumber2 = 0.1D * 42D; - float floatNumber = 0.1F * 42F; - - // 1. Displays: 4.2 != 4.2000002861023 - Console.WriteLine( - $"{decimalNumber} != {(decimal)doubleNumber1}"); - - // 2. Displays: 4.2 != 4.200000286102295 - Console.WriteLine( - $"{(double)decimalNumber} != {doubleNumber1}"); - - // 3. Displays: (float)4.2M != 4.2000003F - Console.WriteLine( - $"(float){(float)decimalNumber}M != {floatNumber}F"); - - // 4. Displays: 4.200000286102295 != 4.2 - Console.WriteLine( - $"{doubleNumber1} != {doubleNumber2}"); - - // 5. Displays: 4.2000003F != 4.2D - Console.WriteLine( - $"{floatNumber}F != {doubleNumber2}D"); - - // 6. Displays: 4.199999809265137 != 4.2 - Console.WriteLine( - $"{(double)4.2F} != {4.2D}"); - - // 7. Displays: 4.2F != 4.2D - Console.WriteLine( - $"{4.2F}F != {4.2D}D"); - #endregion INCLUDE - } + #region INCLUDE + decimal decimalNumber = 4.2M; + double doubleNumber1 = 0.1F * 42F; + double doubleNumber2 = 0.1D * 42D; + float floatNumber = 0.1F * 42F; + + // 1. Displays: 4.2 != 4.2000002861023 + Console.WriteLine( + $"{decimalNumber} != {(decimal)doubleNumber1}"); + + // 2. Displays: 4.2 != 4.200000286102295 + Console.WriteLine( + $"{(double)decimalNumber} != {doubleNumber1}"); + + // 3. Displays: (float)4.2M != 4.2000003F + Console.WriteLine( + $"(float){(float)decimalNumber}M != {floatNumber}F"); + + // 4. Displays: 4.200000286102295 != 4.2 + Console.WriteLine( + $"{doubleNumber1} != {doubleNumber2}"); + + // 5. Displays: 4.2000003F != 4.2D + Console.WriteLine( + $"{floatNumber}F != {doubleNumber2}D"); + + // 6. Displays: 4.199999809265137 != 4.2 + Console.WriteLine( + $"{(double)4.2F} != {4.2D}"); + + // 7. Displays: 4.2F != 4.2D + Console.WriteLine( + $"{4.2F}F != {4.2D}D"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.08.DivisionByZero.cs b/src/Chapter04/Listing04.08.DivisionByZero.cs index e6931753e..3b9b3fe90 100644 --- a/src/Chapter04/Listing04.08.DivisionByZero.cs +++ b/src/Chapter04/Listing04.08.DivisionByZero.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_08; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - float n = 0f; - // Displays: NaN - Console.WriteLine(n / 0); - #endregion INCLUDE - } + #region INCLUDE + float n = 0f; + // Displays: NaN + Console.WriteLine(n / 0); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.09.BoundOverflow.cs b/src/Chapter04/Listing04.09.BoundOverflow.cs index 1a673aef9..7cc2dca48 100644 --- a/src/Chapter04/Listing04.09.BoundOverflow.cs +++ b/src/Chapter04/Listing04.09.BoundOverflow.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_09; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - // Displays: -Infinity - Console.WriteLine(-1f / 0); - // Displays: Infinity - Console.WriteLine(3.402823E+38f * 2f); - #endregion INCLUDE - } + #region INCLUDE + // Displays: -Infinity + Console.WriteLine(-1f / 0); + // Displays: Infinity + Console.WriteLine(3.402823E+38f * 2f); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.10.Increment.cs b/src/Chapter04/Listing04.10.Increment.cs index 958464cc4..301da4b7d 100644 --- a/src/Chapter04/Listing04.10.Increment.cs +++ b/src/Chapter04/Listing04.10.Increment.cs @@ -1,15 +1,14 @@ // Justification: Demonstrating the without += just prior showing += #pragma warning disable IDE0054 // Use compound assignment -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_10; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int x = 123; - x = x + 2; - #endregion INCLUDE - } + #region INCLUDE + int x = 123; + x = x + 2; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.11.IncrementOperator.cs b/src/Chapter04/Listing04.11.IncrementOperator.cs index 21277c39e..fb233d652 100644 --- a/src/Chapter04/Listing04.11.IncrementOperator.cs +++ b/src/Chapter04/Listing04.11.IncrementOperator.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_11; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int x = 123; - x += 2; - #endregion INCLUDE - } + #region INCLUDE + int x = 123; + x += 2; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.12.OtherOperators.cs b/src/Chapter04/Listing04.12.OtherOperators.cs index 3d56f9d3f..68eadf7c5 100644 --- a/src/Chapter04/Listing04.12.OtherOperators.cs +++ b/src/Chapter04/Listing04.12.OtherOperators.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_12; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - int x = 0; + int x = 0; - #region INCLUDE - x -= 2; - x /= 2; - x *= 2; - x %= 2; - #endregion INCLUDE - } + #region INCLUDE + x -= 2; + x /= 2; + x *= 2; + x %= 2; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.13.UnaryIncrement.cs b/src/Chapter04/Listing04.13.UnaryIncrement.cs index da4355a30..7ba7e0929 100644 --- a/src/Chapter04/Listing04.13.UnaryIncrement.cs +++ b/src/Chapter04/Listing04.13.UnaryIncrement.cs @@ -1,18 +1,17 @@ // Justification: Demonstrating the equivalent operators #pragma warning disable IDE0054 // Use compound assignment -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_13; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - int spaceCount = 0; + int spaceCount = 0; - #region INCLUDE - spaceCount = spaceCount + 1; - spaceCount += 1; - spaceCount++; - #endregion INCLUDE - } + #region INCLUDE + spaceCount = spaceCount + 1; + spaceCount += 1; + spaceCount++; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.14.UnaryDecrement.cs b/src/Chapter04/Listing04.14.UnaryDecrement.cs index c41a1af4c..9fab1bbbc 100644 --- a/src/Chapter04/Listing04.14.UnaryDecrement.cs +++ b/src/Chapter04/Listing04.14.UnaryDecrement.cs @@ -1,18 +1,17 @@ // Justification: Demonstrating equivalent operators. #pragma warning disable IDE0054 // Use compound assignment -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_14; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - int lines = 0; + int lines = 0; - #region INCLUDE - lines = lines - 1; - lines -= 1; - lines--; - #endregion INCLUDE - } + #region INCLUDE + lines = lines - 1; + lines -= 1; + lines--; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.15.DisplayUnicode.cs b/src/Chapter04/Listing04.15.DisplayUnicode.cs index 24dae3f8d..396bcbddf 100644 --- a/src/Chapter04/Listing04.15.DisplayUnicode.cs +++ b/src/Chapter04/Listing04.15.DisplayUnicode.cs @@ -1,27 +1,26 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_15; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - char current; - int unicodeValue; + #region INCLUDE + char current; + int unicodeValue; - // Set the initial value of current - current = 'z'; + // Set the initial value of current + current = 'z'; - do - { - // Retrieve the Unicode value of current - unicodeValue = current; - Console.Write($"{current}={unicodeValue}\t"); + do + { + // Retrieve the Unicode value of current + unicodeValue = current; + Console.Write($"{current}={unicodeValue}\t"); - // Proceed to the previous letter in the alphabet - current--; - } - while(current >= 'a'); - #endregion INCLUDE + // Proceed to the previous letter in the alphabet + current--; } + while(current >= 'a'); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.16.PostIncrement.cs b/src/Chapter04/Listing04.16.PostIncrement.cs index 1df025945..039c40202 100644 --- a/src/Chapter04/Listing04.16.PostIncrement.cs +++ b/src/Chapter04/Listing04.16.PostIncrement.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_16; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int count = 123; - int result; - result = count++; - Console.WriteLine( - $"result = {result} and count = {count}"); - #endregion INCLUDE - } + #region INCLUDE + int count = 123; + int result; + result = count++; + Console.WriteLine( + $"result = {result} and count = {count}"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.17.PreIncrement.cs b/src/Chapter04/Listing04.17.PreIncrement.cs index 0fbe02abf..cc9838b27 100644 --- a/src/Chapter04/Listing04.17.PreIncrement.cs +++ b/src/Chapter04/Listing04.17.PreIncrement.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_17; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int count = 123; - int result; - #region HIGHLIGHT - result = ++count; - #endregion HIGHLIGHT - Console.WriteLine( - $"result = {result} and count = {count}"); - #endregion INCLUDE - } + #region INCLUDE + int count = 123; + int result; + #region HIGHLIGHT + result = ++count; + #endregion HIGHLIGHT + Console.WriteLine( + $"result = {result} and count = {count}"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.18.ComparingPrefixAndPostfix.cs b/src/Chapter04/Listing04.18.ComparingPrefixAndPostfix.cs index bd59b67a9..8cecc2523 100644 --- a/src/Chapter04/Listing04.18.ComparingPrefixAndPostfix.cs +++ b/src/Chapter04/Listing04.18.ComparingPrefixAndPostfix.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_18; + +#region INCLUDE +public class IncrementExample { - #region INCLUDE - public class IncrementExample + public static void Main() { - public static void Main() - { - int x = 123; - // Displays 123, 124, 125 - Console.WriteLine($"{x++}, {x++}, {x}"); - // x now contains the value 125 - // Displays 126, 127, 127 - Console.WriteLine($"{++x}, {++x}, {x}"); - // x now contains the value 127 - } + int x = 123; + // Displays 123, 124, 125 + Console.WriteLine($"{x++}, {x++}, {x}"); + // x now contains the value 125 + // Displays 126, 127, 127 + Console.WriteLine($"{++x}, {++x}, {x}"); + // x now contains the value 127 } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter04/Listing04.19.DeclaringConstants.cs b/src/Chapter04/Listing04.19.DeclaringConstants.cs index 141a2055a..9028be006 100644 --- a/src/Chapter04/Listing04.19.DeclaringConstants.cs +++ b/src/Chapter04/Listing04.19.DeclaringConstants.cs @@ -2,16 +2,15 @@ #pragma warning disable CS0219 // Variable is assigned but its value is never used #pragma warning disable IDE0059 // Unnecessary assignment of a value -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_19; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - const int secondsPerDay = 60 * 60 * 24; - const int secondsPerWeek = secondsPerDay * 7; - #endregion INCLUDE - } + #region INCLUDE + const int secondsPerDay = 60 * 60 * 24; + const int secondsPerWeek = secondsPerDay * 7; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.20.ConstantInterpolatedStrings.cs b/src/Chapter04/Listing04.20.ConstantInterpolatedStrings.cs index b576917e2..8cce00a3a 100644 --- a/src/Chapter04/Listing04.20.ConstantInterpolatedStrings.cs +++ b/src/Chapter04/Listing04.20.ConstantInterpolatedStrings.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_20; + +public class FortyTwo { - public class FortyTwo + public static void Main() { - public static void Main() - { - #region INCLUDE - const string windSpeed = "42"; - const string announcement = $""" + #region INCLUDE + const string windSpeed = "42"; + const string announcement = $""" The original Tacoma Bridge in Washington was brought down by a { windSpeed } mile/hour wind. """; - Console.WriteLine(announcement); - #endregion INCLUDE - } + Console.WriteLine(announcement); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.21.IfElseStatement.cs b/src/Chapter04/Listing04.21.IfElseStatement.cs index 76a956146..b4a45e8d1 100644 --- a/src/Chapter04/Listing04.21.IfElseStatement.cs +++ b/src/Chapter04/Listing04.21.IfElseStatement.cs @@ -1,34 +1,33 @@ // Justification: Checking for null isn't discussed yet. #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_21; + +public class TicTacToe // Declares the TicTacToe class { - public class TicTacToe // Declares the TicTacToe class + public static void Main() // Declares the entry point of the program { - public static void Main() // Declares the entry point of the program - { - #region INCLUDE - string input; + #region INCLUDE + string input; - // Prompt the user to select a 1- or 2- player game - Console.Write($""" + // Prompt the user to select a 1- or 2- player game + Console.Write($""" 1 - Play against the computer 2 - Play against another player. Choose: """ - ); - input = Console.ReadLine(); + ); + input = Console.ReadLine(); - #region HIGHLIGHT - if (input == "1") - // The user selected to play the computer - Console.WriteLine( - "Play against computer selected."); - else - // Default to 2 players (even if user didn't enter 2) - Console.WriteLine( - "Play against another player."); - #endregion HIGHLIGHT - #endregion INCLUDE - } + #region HIGHLIGHT + if (input == "1") + // The user selected to play the computer + Console.WriteLine( + "Play against computer selected."); + else + // Default to 2 players (even if user didn't enter 2) + Console.WriteLine( + "Play against another player."); + #endregion HIGHLIGHT + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.22.NestedIf.cs b/src/Chapter04/Listing04.22.NestedIf.cs index f522b7025..d320088aa 100644 --- a/src/Chapter04/Listing04.22.NestedIf.cs +++ b/src/Chapter04/Listing04.22.NestedIf.cs @@ -1,48 +1,47 @@ // Justification: Checking for null isn't discussed yet. #pragma warning disable CS8604 // Possible null reference argument -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_22; + +public class TicTacToeTrivia { - public class TicTacToeTrivia + public static void Main() { - public static void Main() - { - #region INCLUDE - int input; // Declare a variable to store the input + #region INCLUDE + int input; // Declare a variable to store the input - Console.Write( - "What is the maximum number " + - "of turns in tic-tac-toe?" + - " (Enter 0 to exit.): "); + Console.Write( + "What is the maximum number " + + "of turns in tic-tac-toe?" + + " (Enter 0 to exit.): "); - // int.Parse() converts the ReadLine() - // return to an int data type - input = int.Parse(Console.ReadLine()); + // int.Parse() converts the ReadLine() + // return to an int data type + input = int.Parse(Console.ReadLine()); - // Condition 1. - if (input <= 0) // line 16 - // Input is less than or equal to 0 - Console.WriteLine("Exiting..."); + // Condition 1. + if (input <= 0) // line 16 + // Input is less than or equal to 0 + Console.WriteLine("Exiting..."); + else + // Condition 2. + if (input < 9) // line 20 + // Input is less than 9 + Console.WriteLine( + $"Tic-tac-toe has more than {input}" + + " maximum turns."); else - // Condition 2. - if (input < 9) // line 20 - // Input is less than 9 + // Condition 3. + if (input > 9) // line 26 + // Input is greater than 9 Console.WriteLine( - $"Tic-tac-toe has more than {input}" + + $"Tic-tac-toe has fewer than {input}" + " maximum turns."); + // Condition 4. else - // Condition 3. - if (input > 9) // line 26 - // Input is greater than 9 - Console.WriteLine( - $"Tic-tac-toe has fewer than {input}" + - " maximum turns."); - // Condition 4. - else - // Input equals 9 - Console.WriteLine( // line 33 - "Correct, tic-tac-toe " + - "has a maximum of 9 turns."); - #endregion INCLUDE - } - } + // Input equals 9 + Console.WriteLine( // line 33 + "Correct, tic-tac-toe " + + "has a maximum of 9 turns."); + #endregion INCLUDE + } } diff --git a/src/Chapter04/Listing04.23.IfElseSequence.cs b/src/Chapter04/Listing04.23.IfElseSequence.cs index 6ea412eb5..72a2e8109 100644 --- a/src/Chapter04/Listing04.23.IfElseSequence.cs +++ b/src/Chapter04/Listing04.23.IfElseSequence.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_23; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - int input = int.Parse(args[0]); - #region INCLUDE - if (input < 0) - Console.WriteLine("Exiting..."); - else if(input < 9) - Console.WriteLine( - $"Tic-tac-toe has more than {input}" + - " maximum turns."); - else if (input > 9) - Console.WriteLine( - $"Tic-tac-toe has less than {input}" + - " maximum turns."); - else - Console.WriteLine( - "Correct, tic-tac-toe has a maximum" + - " of 9 turns."); - #endregion INCLUDE - } + int input = int.Parse(args[0]); + #region INCLUDE + if (input < 0) + Console.WriteLine("Exiting..."); + else if(input < 9) + Console.WriteLine( + $"Tic-tac-toe has more than {input}" + + " maximum turns."); + else if (input > 9) + Console.WriteLine( + $"Tic-tac-toe has less than {input}" + + " maximum turns."); + else + Console.WriteLine( + "Correct, tic-tac-toe has a maximum" + + " of 9 turns."); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.24.NoCodeBlock.cs b/src/Chapter04/Listing04.24.NoCodeBlock.cs index fe4cbaa24..395bef295 100644 --- a/src/Chapter04/Listing04.24.NoCodeBlock.cs +++ b/src/Chapter04/Listing04.24.NoCodeBlock.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_24 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_24; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - int input = int.Parse(args[0]); + int input = int.Parse(args[0]); - #region INCLUDE - if (input < 9) - #region HIGHLIGHT - Console.WriteLine("Exiting"); - #endregion HIGHLIGHT - #endregion INCLUDE - } + #region INCLUDE + if (input < 9) + #region HIGHLIGHT + Console.WriteLine("Exiting"); + #endregion HIGHLIGHT + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.25.WithCodeBlock.cs b/src/Chapter04/Listing04.25.WithCodeBlock.cs index ad6232e7c..07ac04e69 100644 --- a/src/Chapter04/Listing04.25.WithCodeBlock.cs +++ b/src/Chapter04/Listing04.25.WithCodeBlock.cs @@ -2,37 +2,36 @@ #pragma warning disable CS8604 // Possible null reference argument #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_25 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_25; + +public class CircleAreaCalculator { - public class CircleAreaCalculator + public static void Main() { - public static void Main() - { - #region INCLUDE - double radius; // Declare a variable to store the radius - double area; // Declare a variable to store the area + #region INCLUDE + double radius; // Declare a variable to store the radius + double area; // Declare a variable to store the area - Console.Write("Enter the radius of the circle: "); + Console.Write("Enter the radius of the circle: "); - // double.Parse converts the ReadLine() - // return to a double - string temp = Console.ReadLine(); - radius = double.Parse(temp); - if(radius >= 0) - #region HIGHLIGHT - { - // Calculate the area of the circle - area = Math.PI * radius * radius; - Console.WriteLine( - $"The area of the circle is: {area:0.00}"); - } - #endregion HIGHLIGHT - else - { - Console.WriteLine( - $"{radius} is not a valid radius."); - } - #endregion INCLUDE + // double.Parse converts the ReadLine() + // return to a double + string temp = Console.ReadLine(); + radius = double.Parse(temp); + if(radius >= 0) + #region HIGHLIGHT + { + // Calculate the area of the circle + area = Math.PI * radius * radius; + Console.WriteLine( + $"The area of the circle is: {area:0.00}"); + } + #endregion HIGHLIGHT + else + { + Console.WriteLine( + $"{radius} is not a valid radius."); } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.26.RelyingOnIndentation.cs b/src/Chapter04/Listing04.26.RelyingOnIndentation.cs index f7bad666e..45eb4a78f 100644 --- a/src/Chapter04/Listing04.26.RelyingOnIndentation.cs +++ b/src/Chapter04/Listing04.26.RelyingOnIndentation.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_26 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_26; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - double radius = -1; - double area = 0; + double radius = -1; + double area = 0; - #region INCLUDE - if (radius >= 0) - area = Math.PI * radius * radius; - Console.WriteLine( - $"The area of the circle is: {area:0.00}"); - #endregion INCLUDE - } + #region INCLUDE + if (radius >= 0) + area = Math.PI * radius * radius; + Console.WriteLine( + $"The area of the circle is: {area:0.00}"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.27.IfStatementWithCurlyBraces.cs b/src/Chapter04/Listing04.27.IfStatementWithCurlyBraces.cs index ad6436f07..113cca55f 100644 --- a/src/Chapter04/Listing04.27.IfStatementWithCurlyBraces.cs +++ b/src/Chapter04/Listing04.27.IfStatementWithCurlyBraces.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_27 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_27; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - double radius = -1; - double area = 0; + double radius = -1; + double area = 0; - #region INCLUDE - if (radius >= 0) - { - area = Math.PI * radius * radius; - } - Console.WriteLine( - $"The area of the circle is: {area:0.00}"); - #endregion INCLUDE + #region INCLUDE + if (radius >= 0) + { + area = Math.PI * radius * radius; } + Console.WriteLine( + $"The area of the circle is: {area:0.00}"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.28.OutOfScope.cs b/src/Chapter04/Listing04.28.OutOfScope.cs index 71f1de5b1..f073f0a85 100644 --- a/src/Chapter04/Listing04.28.OutOfScope.cs +++ b/src/Chapter04/Listing04.28.OutOfScope.cs @@ -5,37 +5,36 @@ // Justification: Attempting to use message outside of it's scope so it goes unused. #pragma warning disable CS0219 // Variable is assigned but its value is never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_28 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_28; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) + #region INCLUDE + string playerCount; + Console.Write( + "Enter the number of players (1 or 2):"); + playerCount = Console.ReadLine(); + if (playerCount != "1" && playerCount != "2") { - #region INCLUDE - string playerCount; - Console.Write( - "Enter the number of players (1 or 2):"); - playerCount = Console.ReadLine(); - if (playerCount != "1" && playerCount != "2") - { - #region HIGHLIGHT - string message = - "You entered an invalid number of players."; - #endregion HIGHLIGHT - } - else - { - // ... - } - #endregion INCLUDE - #if COMPILE_ERRR - #region INCLUDE #region HIGHLIGHT - // ERROR: message is not in scope: - Console.WriteLine(message); + string message = + "You entered an invalid number of players."; #endregion HIGHLIGHT - #endregion INCLUDE - #endif // COMPILE_ERRR } + else + { + // ... + } + #endregion INCLUDE + #if COMPILE_ERRR + #region INCLUDE + #region HIGHLIGHT + // ERROR: message is not in scope: + Console.WriteLine(message); + #endregion HIGHLIGHT + #endregion INCLUDE + #endif // COMPILE_ERRR } } diff --git a/src/Chapter04/Listing04.29.BooleanExpression.cs b/src/Chapter04/Listing04.29.BooleanExpression.cs index 282a53310..35f7936e9 100644 --- a/src/Chapter04/Listing04.29.BooleanExpression.cs +++ b/src/Chapter04/Listing04.29.BooleanExpression.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_29 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_29; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - int input = 5; + int input = 5; - #region INCLUDE - #region HIGHLIGHT - if (input < 9) - #endregion HIGHLIGHT - { - // Input is less than 9 - Console.WriteLine( - $"Tic-tac-toe has more than {input}" + - " maximum turns."); - } - // ... - #endregion INCLUDE + #region INCLUDE + #region HIGHLIGHT + if (input < 9) + #endregion HIGHLIGHT + { + // Input is less than 9 + Console.WriteLine( + $"Tic-tac-toe has more than {input}" + + " maximum turns."); } + // ... + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.30.AssignmentAsCondition.cs b/src/Chapter04/Listing04.30.AssignmentAsCondition.cs index 7f58b0f5a..2ea73d8d5 100644 --- a/src/Chapter04/Listing04.30.AssignmentAsCondition.cs +++ b/src/Chapter04/Listing04.30.AssignmentAsCondition.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_30 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_30; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - /* - #region INCLUDE - if (input = 9) // Allowed in C++, not in C# - System.Console.WriteLine( - "Correct, tic-tac-toe has a maximum of 9 turns."); - #endregion INCLUDE - */ - } + /* + #region INCLUDE + if (input = 9) // Allowed in C++, not in C# + System.Console.WriteLine( + "Correct, tic-tac-toe has a maximum of 9 turns."); + #endregion INCLUDE + */ } } diff --git a/src/Chapter04/Listing04.31.AssignAsBool.cs b/src/Chapter04/Listing04.31.AssignAsBool.cs index b31e03560..82db9f1b6 100644 --- a/src/Chapter04/Listing04.31.AssignAsBool.cs +++ b/src/Chapter04/Listing04.31.AssignAsBool.cs @@ -1,14 +1,13 @@ #pragma warning disable CS0219 // Variable is assigned but its value is never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_31 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_31; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - bool result = 70 > 7; - #endregion INCLUDE - } + #region INCLUDE + bool result = 70 > 7; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.32.EqualityOperator.cs b/src/Chapter04/Listing04.32.EqualityOperator.cs index d96fe3d96..b18b9a3f6 100644 --- a/src/Chapter04/Listing04.32.EqualityOperator.cs +++ b/src/Chapter04/Listing04.32.EqualityOperator.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_32 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_32; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) + string input = args[0]; + string currentPlayer = args[1]; + #region INCLUDE + if (input.Length == 0 || input == "quit") { - string input = args[0]; - string currentPlayer = args[1]; - #region INCLUDE - if (input.Length == 0 || input == "quit") - { - Console.WriteLine($"Player {currentPlayer} quit!!"); - } - #endregion INCLUDE + Console.WriteLine($"Player {currentPlayer} quit!!"); } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.33.OrOperator.cs b/src/Chapter04/Listing04.33.OrOperator.cs index 278aa390d..4f2d31eac 100644 --- a/src/Chapter04/Listing04.33.OrOperator.cs +++ b/src/Chapter04/Listing04.33.OrOperator.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_33 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_33; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - int hourOfTheDay = int.Parse(args[0]); + int hourOfTheDay = int.Parse(args[0]); - #region INCLUDE - if ((hourOfTheDay > 23) || (hourOfTheDay < 0)) - Console.WriteLine("The time you entered is invalid."); - #endregion INCLUDE - } + #region INCLUDE + if ((hourOfTheDay > 23) || (hourOfTheDay < 0)) + Console.WriteLine("The time you entered is invalid."); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.34.AndOperator.cs b/src/Chapter04/Listing04.34.AndOperator.cs index bd1ed7956..0c3abf48e 100644 --- a/src/Chapter04/Listing04.34.AndOperator.cs +++ b/src/Chapter04/Listing04.34.AndOperator.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_34 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_34; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - int hourOfTheDay = int.Parse(args[0]); + int hourOfTheDay = int.Parse(args[0]); - #region INCLUDE - if ((10 < hourOfTheDay) && (hourOfTheDay < 24)) - Console.WriteLine( - "Hi-Ho, Hi-Ho, it's off to work we go."); - #endregion INCLUDE - } + #region INCLUDE + if ((10 < hourOfTheDay) && (hourOfTheDay < 24)) + Console.WriteLine( + "Hi-Ho, Hi-Ho, it's off to work we go."); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.35.LogicalNegationOperator.cs b/src/Chapter04/Listing04.35.LogicalNegationOperator.cs index 9cb7df813..ae7b414a4 100644 --- a/src/Chapter04/Listing04.35.LogicalNegationOperator.cs +++ b/src/Chapter04/Listing04.35.LogicalNegationOperator.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_35 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_35; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - bool valid = false; - #region HIGHLIGHT - bool result = !valid; - #endregion HIGHLIGHT - // Displays "result = True" - Console.WriteLine($"result = { result }"); - #endregion INCLUDE - } + #region INCLUDE + bool valid = false; + #region HIGHLIGHT + bool result = !valid; + #endregion HIGHLIGHT + // Displays "result = True" + Console.WriteLine($"result = { result }"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.36.ConditionalOperator.cs b/src/Chapter04/Listing04.36.ConditionalOperator.cs index b62b7880d..b13cd7a5a 100644 --- a/src/Chapter04/Listing04.36.ConditionalOperator.cs +++ b/src/Chapter04/Listing04.36.ConditionalOperator.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_36 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_36; + +#region INCLUDE +public class TicTacToe { - #region INCLUDE - public class TicTacToe + public static void Main() { - public static void Main() - { - // Initially set the currentPlayer to Player 1 - int currentPlayer = 1; + // Initially set the currentPlayer to Player 1 + int currentPlayer = 1; - // ... + // ... - for(int turn = 1; turn <= 10; turn++) - { - // ... + for(int turn = 1; turn <= 10; turn++) + { + // ... - // Switch players - currentPlayer = (currentPlayer == 2) ? 1 : 2; - } + // Switch players + currentPlayer = (currentPlayer == 2) ? 1 : 2; } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter04/Listing04.37.NullCoalescingOperator.cs b/src/Chapter04/Listing04.37.NullCoalescingOperator.cs index 6fc6c8165..00c1bb3ab 100644 --- a/src/Chapter04/Listing04.37.NullCoalescingOperator.cs +++ b/src/Chapter04/Listing04.37.NullCoalescingOperator.cs @@ -1,45 +1,44 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_37 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_37; + +public class Program { - public class Program + public static void Main() + { + #region INCLUDE + string? fullName = GetSaveFilePath(); + // ... + + // Null-coalescing operator + string fileName = GetFileName() ?? "config.json"; + string directory = GetConfigurationDirectory() ?? + GetApplicationDirectory() ?? + Environment.CurrentDirectory; + + // Null-coalescing assignment operator + fullName ??= $"{ directory }/{ fileName }"; + + // ... + #endregion INCLUDE + + } + + private static string? GetSaveFilePath() + { + throw new NotImplementedException(); + } + + private static string? GetApplicationDirectory() + { + throw new NotImplementedException(); + } + + private static string? GetConfigurationDirectory() + { + throw new NotImplementedException(); + } + + private static string? GetFileName() { - public static void Main() - { - #region INCLUDE - string? fullName = GetSaveFilePath(); - // ... - - // Null-coalescing operator - string fileName = GetFileName() ?? "config.json"; - string directory = GetConfigurationDirectory() ?? - GetApplicationDirectory() ?? - Environment.CurrentDirectory; - - // Null-coalescing assignment operator - fullName ??= $"{ directory }/{ fileName }"; - - // ... - #endregion INCLUDE - - } - - private static string? GetSaveFilePath() - { - throw new NotImplementedException(); - } - - private static string? GetApplicationDirectory() - { - throw new NotImplementedException(); - } - - private static string? GetConfigurationDirectory() - { - throw new NotImplementedException(); - } - - private static string? GetFileName() - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } } diff --git a/src/Chapter04/Listing04.38.NullConditionalOperator.cs b/src/Chapter04/Listing04.38.NullConditionalOperator.cs index 704619fd8..50992c5c7 100644 --- a/src/Chapter04/Listing04.38.NullConditionalOperator.cs +++ b/src/Chapter04/Listing04.38.NullConditionalOperator.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_38 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_38; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - #region INCLUDE - string[]? segments = null; - string? uri = null; + #region INCLUDE + string[]? segments = null; + string? uri = null; - #region EXCLUDE - // Not shown in manuscript since args won't be null in a normal Main method. - segments = args; + #region EXCLUDE + // Not shown in manuscript since args won't be null in a normal Main method. + segments = args; - #endregion EXCLUDE + #endregion EXCLUDE - int? length = segments?.Length; - #region EXCLUDE - // Pattern matching also allows: - // the following but this is not used - // until covering the topic fully in Chapter 7. - if (length is not null and not 0) { /*...*/ } - #endregion EXCLUDE - if (length is not null && length != 0) - { - uri = string.Join('/', segments!); - } + int? length = segments?.Length; + #region EXCLUDE + // Pattern matching also allows: + // the following but this is not used + // until covering the topic fully in Chapter 7. + if (length is not null and not 0) { /*...*/ } + #endregion EXCLUDE + if (length is not null && length != 0) + { + uri = string.Join('/', segments!); + } - if (uri is null || length is 0) - { - Console.WriteLine( - "There were no segments to combine."); - } - else - { - Console.WriteLine( - $"Uri: { uri }"); - } - #endregion INCLUDE + if (uri is null || length is 0) + { + Console.WriteLine( + "There were no segments to combine."); + } + else + { + Console.WriteLine( + $"Uri: { uri }"); } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.39.NullConditionalOperatorWithIndexOperator.cs b/src/Chapter04/Listing04.39.NullConditionalOperatorWithIndexOperator.cs index 975da0b6e..7d2f2967b 100644 --- a/src/Chapter04/Listing04.39.NullConditionalOperatorWithIndexOperator.cs +++ b/src/Chapter04/Listing04.39.NullConditionalOperatorWithIndexOperator.cs @@ -1,42 +1,41 @@ // Justification: Intentionally demonstrating legacy syntax. #pragma warning disable IDE1005 // Delegate invocation can be simplified. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_39 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_39; + +public class Thermostat { - public class Thermostat - { - public event System.EventHandler PropertyChanged = delegate { }; + public event System.EventHandler PropertyChanged = delegate { }; - private int _Temperature; - public int Temperature + private int _Temperature; + public int Temperature + { + get { return _Temperature; } + set { - get { return _Temperature; } - set + #region INCLUDE + System.EventHandler propertyChanged = + PropertyChanged; + if (propertyChanged != null) { - #region INCLUDE - System.EventHandler propertyChanged = - PropertyChanged; - if (propertyChanged != null) - { - propertyChanged(this, - new System.EventArgs()); - } - #endregion INCLUDE - - _Temperature = value; + propertyChanged(this, + new System.EventArgs()); } + #endregion INCLUDE + + _Temperature = value; } + } - int _Humidity; - public int Humidity + int _Humidity; + public int Humidity + { + get { return _Humidity; } + set { - get { return _Humidity; } - set - { - PropertyChanged?.Invoke(this, - new System.EventArgs()); + PropertyChanged?.Invoke(this, + new System.EventArgs()); - _Humidity = value; - } + _Humidity = value; } } } diff --git a/src/Chapter04/Listing04.40.RightShiftOperator.cs b/src/Chapter04/Listing04.40.RightShiftOperator.cs index 5b8f0e72c..9c653e579 100644 --- a/src/Chapter04/Listing04.40.RightShiftOperator.cs +++ b/src/Chapter04/Listing04.40.RightShiftOperator.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_40 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_40; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - int x; - x = (-7 >> 2); // 11111111111111111111111111111001 becomes - // 11111111111111111111111111111110 - // Write out "x is -2." - Console.WriteLine($"x = {x}."); - #endregion INCLUDE - } + #region INCLUDE + int x; + x = (-7 >> 2); // 11111111111111111111111111111001 becomes + // 11111111111111111111111111111110 + // Write out "x is -2." + Console.WriteLine($"x = {x}."); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.41.BitwiseOperators.cs b/src/Chapter04/Listing04.41.BitwiseOperators.cs index 701062263..02bf8319f 100644 --- a/src/Chapter04/Listing04.41.BitwiseOperators.cs +++ b/src/Chapter04/Listing04.41.BitwiseOperators.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_41 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_41; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - byte and, or, xor; - and = 12 & 7; // and = 4 - or = 12 | 7; // or = 15 - xor = 12 ^ 7; // xor = 11 - Console.WriteLine( $""" + #region INCLUDE + byte and, or, xor; + and = 12 & 7; // and = 4 + or = 12 | 7; // or = 15 + xor = 12 ^ 7; // xor = 11 + Console.WriteLine( $""" and = { and } or = { or } xor = { xor } """); - #endregion INCLUDE - } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.42.StringRepresentationOfBinary.cs b/src/Chapter04/Listing04.42.StringRepresentationOfBinary.cs index 760e4185c..a04ad9e90 100644 --- a/src/Chapter04/Listing04.42.StringRepresentationOfBinary.cs +++ b/src/Chapter04/Listing04.42.StringRepresentationOfBinary.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_42 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_42; + +#region INCLUDE +public class BinaryConverter { - #region INCLUDE - public class BinaryConverter + public static void Main() { - public static void Main() - { - const int size = 64; - ulong value; - char bit; + const int size = 64; + ulong value; + char bit; - Console.Write("Enter an integer: "); - // Use long.Parse() to support negative numbers - // Assumes unchecked assignment to ulong - // If ReadLine returns null, use "42" as default input - value = (ulong)long.Parse(Console.ReadLine() ?? "42"); + Console.Write("Enter an integer: "); + // Use long.Parse() to support negative numbers + // Assumes unchecked assignment to ulong + // If ReadLine returns null, use "42" as default input + value = (ulong)long.Parse(Console.ReadLine() ?? "42"); - // Set initial mask to 100.... - ulong mask = 1UL << size - 1; - for(int count = 0; count < size; count++) - { - bit = ((mask & value) != 0) ? '1' : '0'; - Console.Write(bit); - // Shift mask one location over to the right - mask >>= 1; - } - Console.WriteLine(); + // Set initial mask to 100.... + ulong mask = 1UL << size - 1; + for(int count = 0; count < size; count++) + { + bit = ((mask & value) != 0) ? '1' : '0'; + Console.Write(bit); + // Shift mask one location over to the right + mask >>= 1; } + Console.WriteLine(); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter04/Listing04.43.LogicalAssignmentOperators.cs b/src/Chapter04/Listing04.43.LogicalAssignmentOperators.cs index 80b9c5afc..e81b226df 100644 --- a/src/Chapter04/Listing04.43.LogicalAssignmentOperators.cs +++ b/src/Chapter04/Listing04.43.LogicalAssignmentOperators.cs @@ -1,22 +1,21 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_43 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_43; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - byte and = 12, or = 12, xor = 12; - #region HIGHLIGHT - and &= 7; // and = 4 - or |= 7; // or = 15 - xor ^= 7; // xor = 11 - #endregion HIGHLIGHT - Console.WriteLine( $""" + #region INCLUDE + byte and = 12, or = 12, xor = 12; + #region HIGHLIGHT + and &= 7; // and = 4 + or |= 7; // or = 15 + xor ^= 7; // xor = 11 + #endregion HIGHLIGHT + Console.WriteLine( $""" and = {and} or = {or} xor = {xor} """); - #endregion INCLUDE - } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.44.WhileLoop.cs b/src/Chapter04/Listing04.44.WhileLoop.cs index 6260edcbd..b9eb6bd9d 100644 --- a/src/Chapter04/Listing04.44.WhileLoop.cs +++ b/src/Chapter04/Listing04.44.WhileLoop.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_44 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_44; + +public class FibonacciCalculator { - public class FibonacciCalculator + public static void Main() { - public static void Main() - { - #region INCLUDE - decimal current; - decimal previous; - decimal temp; - decimal input; - - Console.Write("Enter a positive integer:"); + #region INCLUDE + decimal current; + decimal previous; + decimal temp; + decimal input; - // decimal.Parse convert the ReadLine to a decimal - // If ReadLine returns null, use "42" as default input - input = decimal.Parse(Console.ReadLine() ?? "42"); + Console.Write("Enter a positive integer:"); - // Initialize current and previous to 1, the first - // two numbers in the Fibonacci series - current = previous = 1; + // decimal.Parse convert the ReadLine to a decimal + // If ReadLine returns null, use "42" as default input + input = decimal.Parse(Console.ReadLine() ?? "42"); - // While the current Fibonacci number in the series is - // less than the value input by the user - while (current <= input) - { - temp = current; - current = previous + current; - previous = temp; // Executes even if previous - // statement caused current to exceed input - } + // Initialize current and previous to 1, the first + // two numbers in the Fibonacci series + current = previous = 1; - Console.WriteLine( - $"The Fibonacci number following this is { current }"); - #endregion INCLUDE + // While the current Fibonacci number in the series is + // less than the value input by the user + while (current <= input) + { + temp = current; + current = previous + current; + previous = temp; // Executes even if previous + // statement caused current to exceed input } + + Console.WriteLine( + $"The Fibonacci number following this is { current }"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.45.DoWhileLoop.cs b/src/Chapter04/Listing04.45.DoWhileLoop.cs index 0a6eed4fb..fa3140ea1 100644 --- a/src/Chapter04/Listing04.45.DoWhileLoop.cs +++ b/src/Chapter04/Listing04.45.DoWhileLoop.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_45 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_45; + +public class Program { - public class Program + public static void Main() { - public static void Main() + int currentPlayer = 1; + #region INCLUDE + // Repeatedly request player to move until he + // enters a valid position on the board + bool valid; + do { - int currentPlayer = 1; - #region INCLUDE - // Repeatedly request player to move until he - // enters a valid position on the board - bool valid; - do - { - valid = false; + valid = false; - // Request a move from the current player - Console.Write( - $"Player {currentPlayer}: Enter move:"); - string? input = Console.ReadLine(); + // Request a move from the current player + Console.Write( + $"Player {currentPlayer}: Enter move:"); + string? input = Console.ReadLine(); - // Check the current player's input - // ... + // Check the current player's input + // ... - } while(!valid); - #endregion INCLUDE - } + } while(!valid); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.46.ForLoop.cs b/src/Chapter04/Listing04.46.ForLoop.cs index af2691890..6956f7c5e 100644 --- a/src/Chapter04/Listing04.46.ForLoop.cs +++ b/src/Chapter04/Listing04.46.ForLoop.cs @@ -1,30 +1,29 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_46 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_46; + +public class BinaryConverter { - public class BinaryConverter + public static void Main() { - public static void Main() - { - #region INCLUDE - const int size = 64; // Also available from sizeof(ulong) - ulong value; - char bit; + #region INCLUDE + const int size = 64; // Also available from sizeof(ulong) + ulong value; + char bit; - Console.Write("Enter an integer: "); - // Use long.Parse() to support negative numbers - // Assumes unchecked assignment to ulong - // If ReadLine returns null, use "42" as default input - value = (ulong)long.Parse(Console.ReadLine() ?? "42"); + Console.Write("Enter an integer: "); + // Use long.Parse() to support negative numbers + // Assumes unchecked assignment to ulong + // If ReadLine returns null, use "42" as default input + value = (ulong)long.Parse(Console.ReadLine() ?? "42"); - // Set initial mask to 100.... - ulong mask = 1UL << size - 1; - for(int count = 0; count < size; count++) - { - bit = ((mask & value) > 0) ? '1' : '0'; - Console.Write(bit); - // Shift mask one location over to the right - mask >>= 1; - } - #endregion INCLUDE + // Set initial mask to 100.... + ulong mask = 1UL << size - 1; + for(int count = 0; count < size; count++) + { + bit = ((mask & value) > 0) ? '1' : '0'; + Console.Write(bit); + // Shift mask one location over to the right + mask >>= 1; } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.47.ForWithMultipleExpressions.cs b/src/Chapter04/Listing04.47.ForWithMultipleExpressions.cs index 3374be154..5314dbcb6 100644 --- a/src/Chapter04/Listing04.47.ForWithMultipleExpressions.cs +++ b/src/Chapter04/Listing04.47.ForWithMultipleExpressions.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_47 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_47; + +public class Program { - public class Program + public static void Main() { - public static void Main() + #region INCLUDE + for (int x = 0, y = 5; ((x <= 5) && (y >= 0)); y--, x++) { - #region INCLUDE - for (int x = 0, y = 5; ((x <= 5) && (y >= 0)); y--, x++) - { - Console.Write( - $"{ x }{ ((x > y) ? '>' : '<')}{ y }\t"); - } - #endregion INCLUDE + Console.Write( + $"{ x }{ ((x > y) ? '>' : '<')}{ y }\t"); } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.48.DeterminingRemainingMoves.cs b/src/Chapter04/Listing04.48.DeterminingRemainingMoves.cs index 9d57699c6..70ada8ae1 100644 --- a/src/Chapter04/Listing04.48.DeterminingRemainingMoves.cs +++ b/src/Chapter04/Listing04.48.DeterminingRemainingMoves.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_48 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_48; + +public class TicTacToe // Declares the TicTacToe class { - public class TicTacToe // Declares the TicTacToe class + public static void Main() // Declares the entry point of the program { - public static void Main() // Declares the entry point of the program - { - #region INCLUDE - // Hardcode initial board as follows - // ---+---+--- - // 1 | 2 | 3 - // ---+---+--- - // 4 | 5 | 6 - // ---+---+--- - // 7 | 8 | 9 - // ---+---+--- - char[] cells = { - '1', '2', '3', '4', '5', '6', '7', '8', '9' - }; + #region INCLUDE + // Hardcode initial board as follows + // ---+---+--- + // 1 | 2 | 3 + // ---+---+--- + // 4 | 5 | 6 + // ---+---+--- + // 7 | 8 | 9 + // ---+---+--- + char[] cells = { + '1', '2', '3', '4', '5', '6', '7', '8', '9' + }; - Console.Write( - "The available moves are as follows: "); + Console.Write( + "The available moves are as follows: "); - // Write out the initial available moves - foreach(char cell in cells) + // Write out the initial available moves + foreach(char cell in cells) + { + if(cell != 'O' && cell != 'X') { - if(cell != 'O' && cell != 'X') - { - Console.Write($"{ cell } "); - } + Console.Write($"{ cell } "); } - #endregion INCLUDE } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.49.InputValidation.cs b/src/Chapter04/Listing04.49.InputValidation.cs index c91f57677..b4b6b6fa7 100644 --- a/src/Chapter04/Listing04.49.InputValidation.cs +++ b/src/Chapter04/Listing04.49.InputValidation.cs @@ -1,44 +1,43 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_49 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_49; + +public class Program { - public class Program + public static void Main(params string[] args) { - public static void Main(params string[] args) + string input = args[0]; + #region INCLUDE + // ... + + // Check the current player's input + if ((input == "1") || + (input == "2") || + (input == "3") || + (input == "4") || + (input == "5") || + (input == "6") || + (input == "7") || + (input == "8") || + (input == "9")) { - string input = args[0]; - #region INCLUDE + // Save/move as the player directed // ... - // Check the current player's input - if ((input == "1") || - (input == "2") || - (input == "3") || - (input == "4") || - (input == "5") || - (input == "6") || - (input == "7") || - (input == "8") || - (input == "9")) - { - // Save/move as the player directed - // ... - - } - else if((input.Length == 0) || (input == "quit")) - { - // Retry or quite - // ... + } + else if((input.Length == 0) || (input == "quit")) + { + // Retry or quite + // ... - } - else - { - Console.WriteLine( $""" + } + else + { + Console.WriteLine( $""" ERROR: Enter a value from 1-9. Push ENTER to quit """); - } - - // ... - #endregion INCLUDE } + + // ... + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.50.SwitchStatement.cs b/src/Chapter04/Listing04.50.SwitchStatement.cs index 7138d0580..d5d2a551c 100644 --- a/src/Chapter04/Listing04.50.SwitchStatement.cs +++ b/src/Chapter04/Listing04.50.SwitchStatement.cs @@ -1,49 +1,48 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_50 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_50; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - // ... - } - - #region INCLUDE - public static bool ValidateAndMove( - int[] playerPositions, int currentPlayer, string input) - { - bool valid = false; + // ... + } - // Check the current player's input - switch(input) - { - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - // Save/move as the player directed - // ... - valid = true; - break; - case "": - case "quit": - valid = true; - break; - default: - // If none of the other case statements - // is encountered then the text is invalid - Console.WriteLine( - "ERROR: Enter a value from 1-9. " - + "Push ENTER to quit"); - break; - } + #region INCLUDE + public static bool ValidateAndMove( + int[] playerPositions, int currentPlayer, string input) + { + bool valid = false; - return valid; + // Check the current player's input + switch(input) + { + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + // Save/move as the player directed + // ... + valid = true; + break; + case "": + case "quit": + valid = true; + break; + default: + // If none of the other case statements + // is encountered then the text is invalid + Console.WriteLine( + "ERROR: Enter a value from 1-9. " + + "Push ENTER to quit"); + break; } - #endregion INCLUDE + + return valid; } + #endregion INCLUDE } diff --git a/src/Chapter04/Listing04.51.BreakStatement.cs b/src/Chapter04/Listing04.51.BreakStatement.cs index 71c6bbfed..6d1411453 100644 --- a/src/Chapter04/Listing04.51.BreakStatement.cs +++ b/src/Chapter04/Listing04.51.BreakStatement.cs @@ -1,54 +1,53 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_51 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_51; + +public class TicTacToe // Declares the TicTacToe class { - public class TicTacToe // Declares the TicTacToe class + public static void Main() // Declares the entry point of the program { - public static void Main() // Declares the entry point of the program - { - #region INCLUDE - int winner = 0; - // Stores locations each player has moved - int[] playerPositions = { 0, 0 }; + #region INCLUDE + int winner = 0; + // Stores locations each player has moved + int[] playerPositions = { 0, 0 }; - // Hardcoded board position - // X | 2 | O - // ---+---+--- - // O | O | 6 - // ---+---+--- - // X | X | X - playerPositions[0] = 449; - playerPositions[1] = 28; + // Hardcoded board position + // X | 2 | O + // ---+---+--- + // O | O | 6 + // ---+---+--- + // X | X | X + playerPositions[0] = 449; + playerPositions[1] = 28; - // Determine if there is a winner - int[] winningMasks = { - 7, 56, 448, 73, 146, 292, 84, 273 }; + // Determine if there is a winner + int[] winningMasks = { + 7, 56, 448, 73, 146, 292, 84, 273 }; - // Iterate through each winning mask to determine - // if there is a winner - #region HIGHLIGHT - foreach (int mask in winningMasks) + // Iterate through each winning mask to determine + // if there is a winner + #region HIGHLIGHT + foreach (int mask in winningMasks) + { + #endregion HIGHLIGHT + if ((mask & playerPositions[0]) == mask) { + winner = 1; + #region HIGHLIGHT + break; #endregion HIGHLIGHT - if ((mask & playerPositions[0]) == mask) - { - winner = 1; - #region HIGHLIGHT - break; - #endregion HIGHLIGHT - } - else if((mask & playerPositions[1]) == mask) - { - winner = 2; - #region HIGHLIGHT - break; - #endregion HIGHLIGHT - } + } + else if((mask & playerPositions[1]) == mask) + { + winner = 2; #region HIGHLIGHT + break; + #endregion HIGHLIGHT } - #endregion HIGHLIGHT - - Console.WriteLine( - $"Player { winner } was the winner"); - #endregion INCLUDE + #region HIGHLIGHT } + #endregion HIGHLIGHT + + Console.WriteLine( + $"Player { winner } was the winner"); + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.52.SettingABit.cs b/src/Chapter04/Listing04.52.SettingABit.cs index 9283775f1..4a2260d08 100644 --- a/src/Chapter04/Listing04.52.SettingABit.cs +++ b/src/Chapter04/Listing04.52.SettingABit.cs @@ -1,35 +1,34 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_52 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_52; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - int[] playerPositions = { 0, 0 }; - int currentPlayer = 1; - string input = ""; + int[] playerPositions = { 0, 0 }; + int currentPlayer = 1; + string input = ""; - #region INCLUDE - int shifter; // The number of places to shift - // over to set a bit - int position; // The bit that is to be set + #region INCLUDE + int shifter; // The number of places to shift + // over to set a bit + int position; // The bit that is to be set - // int.Parse() converts "input" to an integer. - // "int.Parse(input) - 1" because arrays - // are zero based. - shifter = int.Parse(input) - 1; + // int.Parse() converts "input" to an integer. + // "int.Parse(input) - 1" because arrays + // are zero based. + shifter = int.Parse(input) - 1; - // Shift mask of 00000000000000000000000000000001 - // over by cellLocations. - position = 1 << shifter; + // Shift mask of 00000000000000000000000000000001 + // over by cellLocations. + position = 1 << shifter; - // Take the current player cells and OR them to set the - // new position as well. - // Since currentPlayer is either 1 or 2, - // subtract 1 to use currentPlayer as an - // index in a zero based array. - playerPositions[currentPlayer - 1] |= position; - #endregion INCLUDE - } + // Take the current player cells and OR them to set the + // new position as well. + // Since currentPlayer is either 1 or 2, + // subtract 1 to use currentPlayer as an + // index in a zero based array. + playerPositions[currentPlayer - 1] |= position; + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.53.DeterminingEmailDomain.cs b/src/Chapter04/Listing04.53.DeterminingEmailDomain.cs index 93c101be9..af146c438 100644 --- a/src/Chapter04/Listing04.53.DeterminingEmailDomain.cs +++ b/src/Chapter04/Listing04.53.DeterminingEmailDomain.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_53 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_53; + +public class EmailDomain { - public class EmailDomain + public static void Main() { - public static void Main() - { - #region INCLUDE - string email; - bool insideDomain = false; + #region INCLUDE + string email; + bool insideDomain = false; - Console.Write("Enter an email address: "); - email = Console.ReadLine() ?? string.Empty; + Console.Write("Enter an email address: "); + email = Console.ReadLine() ?? string.Empty; - Console.Write("The email domain is: "); + Console.Write("The email domain is: "); - // Iterate through each letter in the email address - foreach(char letter in email) + // Iterate through each letter in the email address + foreach(char letter in email) + { + if(!insideDomain) { - if(!insideDomain) + if(letter == '@') { - if(letter == '@') - { - insideDomain = true; - } - continue; + insideDomain = true; } - - Console.Write(letter); + continue; } - #endregion INCLUDE + + Console.Write(letter); } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.54.ReplacingContinueWithIf.cs b/src/Chapter04/Listing04.54.ReplacingContinueWithIf.cs index 3ca18a903..54a3cf078 100644 --- a/src/Chapter04/Listing04.54.ReplacingContinueWithIf.cs +++ b/src/Chapter04/Listing04.54.ReplacingContinueWithIf.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_54 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_54; + +public class EmailDomain { - public class EmailDomain + public static void Main() { - public static void Main() - { - string email; - bool insideDomain = false; + string email; + bool insideDomain = false; - Console.WriteLine("Enter an email address: "); - email = Console.ReadLine() ?? string.Empty; + Console.WriteLine("Enter an email address: "); + email = Console.ReadLine() ?? string.Empty; - Console.Write("The email domain is: "); + Console.Write("The email domain is: "); - #region INCLUDE - // Iterate through each letter in the email address - foreach (char letter in email) + #region INCLUDE + // Iterate through each letter in the email address + foreach (char letter in email) + { + if(insideDomain) { - if(insideDomain) - { - Console.Write(letter); - } - else + Console.Write(letter); + } + else + { + if(letter == '@') { - if(letter == '@') - { - insideDomain = true; - } + insideDomain = true; } } - #endregion INCLUDE } + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.55.GotoStatements.cs b/src/Chapter04/Listing04.55.GotoStatements.cs index 0ff7e7602..c4400302b 100644 --- a/src/Chapter04/Listing04.55.GotoStatements.cs +++ b/src/Chapter04/Listing04.55.GotoStatements.cs @@ -1,54 +1,53 @@ #pragma warning disable CS0219 // Variable is assigned but its value is never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_55 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_55; + +public class Program { - public class Program + #region INCLUDE + // ... + public static void Main(string[] args) { - #region INCLUDE - // ... - public static void Main(string[] args) - { - bool isOutputSet = false; - bool isFiltered = false; - bool isRecursive = false; + bool isOutputSet = false; + bool isFiltered = false; + bool isRecursive = false; - foreach(string option in args) + foreach(string option in args) + { + switch(option) { - switch(option) - { - case "/out": - isOutputSet = true; - isFiltered = false; + case "/out": + isOutputSet = true; + isFiltered = false; + // ... + #region HIGHLIGHT + goto default; + #endregion HIGHLIGHT + case "/f": + isFiltered = true; + isRecursive = false; + // ... + #region HIGHLIGHT + goto default; + #endregion HIGHLIGHT + default: + if(isRecursive) + { + // Recurse down the hierarchy + Console.WriteLine("Recursing..."); // ... - #region HIGHLIGHT - goto default; - #endregion HIGHLIGHT - case "/f": - isFiltered = true; - isRecursive = false; + } + else if(isFiltered) + { + // Add option to list of filters + Console.WriteLine("Filtering..."); // ... - #region HIGHLIGHT - goto default; - #endregion HIGHLIGHT - default: - if(isRecursive) - { - // Recurse down the hierarchy - Console.WriteLine("Recursing..."); - // ... - } - else if(isFiltered) - { - // Add option to list of filters - Console.WriteLine("Filtering..."); - // ... - } - break; - } + } + break; } - - // ... } - #endregion INCLUDE + + // ... } + #endregion INCLUDE } diff --git a/src/Chapter04/Listing04.56.ExcludingCode.cs b/src/Chapter04/Listing04.56.ExcludingCode.cs index a8a74f148..12cdcd3d3 100644 --- a/src/Chapter04/Listing04.56.ExcludingCode.cs +++ b/src/Chapter04/Listing04.56.ExcludingCode.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_56 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_56; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - // ... - #region INCLUDE - #if CSHARP2PLUS - System.Console.Clear(); - #endif - #endregion INCLUDE - // ... - } + // ... + #region INCLUDE + #if CSHARP2PLUS + System.Console.Clear(); + #endif + #endregion INCLUDE + // ... } } diff --git a/src/Chapter04/Listing04.57.Directives.cs b/src/Chapter04/Listing04.57.Directives.cs index 4885c6779..8795e179f 100644 --- a/src/Chapter04/Listing04.57.Directives.cs +++ b/src/Chapter04/Listing04.57.Directives.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_57 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_57; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - #if LINUX - // ... - #elif WINDOWS - // ... - #endif - #endregion INCLUDE - } + #region INCLUDE + #if LINUX + // ... + #elif WINDOWS + // ... + #endif + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.58.DefineDirective.cs b/src/Chapter04/Listing04.58.DefineDirective.cs index 3fdda13d8..d9acb9096 100644 --- a/src/Chapter04/Listing04.58.DefineDirective.cs +++ b/src/Chapter04/Listing04.58.DefineDirective.cs @@ -2,13 +2,12 @@ #define CSHARP2PLUS #endregion INCLUDE -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_58 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_58; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - // ... - } + // ... } } diff --git a/src/Chapter04/Listing04.59.WarningDirective.cs b/src/Chapter04/Listing04.59.WarningDirective.cs index 4a5022fb0..1bb111b1b 100644 --- a/src/Chapter04/Listing04.59.WarningDirective.cs +++ b/src/Chapter04/Listing04.59.WarningDirective.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_59 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_59; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - #warning "Same move allowed multiple times." - #endregion INCLUDE - } + #region INCLUDE + #warning "Same move allowed multiple times." + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.60.PragmaDirective.cs b/src/Chapter04/Listing04.60.PragmaDirective.cs index dfba0fba1..983b4a372 100644 --- a/src/Chapter04/Listing04.60.PragmaDirective.cs +++ b/src/Chapter04/Listing04.60.PragmaDirective.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_60 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_60; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - #pragma warning disable CS1030 - #endregion INCLUDE - } + #region INCLUDE + #pragma warning disable CS1030 + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.61.PragmaRestore.cs b/src/Chapter04/Listing04.61.PragmaRestore.cs index 029b24763..5697f8776 100644 --- a/src/Chapter04/Listing04.61.PragmaRestore.cs +++ b/src/Chapter04/Listing04.61.PragmaRestore.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_61 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_61; + +public class Program { - public class Program - { #pragma warning disable CS1030 - public static void Main() - { + public static void Main() + { #warning "Sample warning suppressed by #pragma warning disable." - } - #region INCLUDE - #pragma warning restore CS1030 - #endregion INCLUDE } + #region INCLUDE + #pragma warning restore CS1030 + #endregion INCLUDE } diff --git a/src/Chapter04/Listing04.62.LineWarning.cs b/src/Chapter04/Listing04.62.LineWarning.cs index 0608067aa..1edd43974 100644 --- a/src/Chapter04/Listing04.62.LineWarning.cs +++ b/src/Chapter04/Listing04.62.LineWarning.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_62 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_62; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - #line 113 "TicTacToe.cs" - #warning "Same move allowed multiple times." - #line default - #endregion INCLUDE - } + #region INCLUDE + #line 113 "TicTacToe.cs" + #warning "Same move allowed multiple times." + #line default + #endregion INCLUDE } } diff --git a/src/Chapter04/Listing04.63.Regions.cs b/src/Chapter04/Listing04.63.Regions.cs index 85deb9f5c..73215dea7 100644 --- a/src/Chapter04/Listing04.63.Regions.cs +++ b/src/Chapter04/Listing04.63.Regions.cs @@ -1,53 +1,52 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_63 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Listing04_63; + +public class Program { - public class Program + public static void Main() { - public static void Main() + // ... + + int border; + string[] borders = { + "|", "|", "\n---+---+---\n", "|", "|", + "\n---+---+---\n", "|", "|", "" + }; + System.Collections.Generic.IEnumerable cells = new char []{ + '1', '2', '3', '4', '5', '6', '7', '8', '9' + }; + + #region INCLUDE + // ... + #region Display Tic-tac-toe Board + + #if CSHARP2PLUS + System.Console.Clear(); + #endif + + // Display the current board + border = 0; // set the first border (border[0] = "|") + + // Display the top line of dashes + // ("\n---+---+---\n") + Console.Write(borders[2]); + foreach(char cell in cells) { - // ... - - int border; - string[] borders = { - "|", "|", "\n---+---+---\n", "|", "|", - "\n---+---+---\n", "|", "|", "" - }; - System.Collections.Generic.IEnumerable cells = new char []{ - '1', '2', '3', '4', '5', '6', '7', '8', '9' - }; - - #region INCLUDE - // ... - #region Display Tic-tac-toe Board - - #if CSHARP2PLUS - System.Console.Clear(); - #endif - - // Display the current board - border = 0; // set the first border (border[0] = "|") - - // Display the top line of dashes - // ("\n---+---+---\n") - Console.Write(borders[2]); - foreach(char cell in cells) - { - // Write out a cell value and the border that comes after it - Console.Write($" { cell } { borders[border] }"); + // Write out a cell value and the border that comes after it + Console.Write($" { cell } { borders[border] }"); - // Increment to the next border - border++; + // Increment to the next border + border++; - // Reset border to 0 if it is 3 - if(border == 3) - { - border = 0; - } + // Reset border to 0 if it is 3 + if(border == 3) + { + border = 0; } + } - #endregion Display Tic-tac-toe Board + #endregion Display Tic-tac-toe Board - // ... - #endregion INCLUDE - } + // ... + #endregion INCLUDE } } diff --git a/src/Chapter04/Table04.04.CheckForNull.cs b/src/Chapter04/Table04.04.CheckForNull.cs index 891012573..28e056339 100644 --- a/src/Chapter04/Table04.04.CheckForNull.cs +++ b/src/Chapter04/Table04.04.CheckForNull.cs @@ -1,103 +1,102 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Table04_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.Table04_04; + +public class Program { - public class Program + public static void PatternMatchingIsNull(string? uri = null!) { - public static void PatternMatchingIsNull(string? uri = null!) + // 1. + if (uri is null) { - // 1. - if (uri is null) - { - Console.WriteLine( - "Uri is null"); - } - else - { - Console.WriteLine( - $"Uri is: {uri}"); - } + Console.WriteLine( + "Uri is null"); } - public static void PatternMatchingIsNotNull(string? uri = null) + else { - // 2. - if (uri is not null) - { - Console.WriteLine( - $"Uri is: {uri}"); - } - else - { - Console.WriteLine( - "Uri is null"); - } + Console.WriteLine( + $"Uri is: {uri}"); } - public static void EqualityInEqualityCheckForNull(string? uri = null) + } + public static void PatternMatchingIsNotNull(string? uri = null) + { + // 2. + if (uri is not null) { - // 3. - if (uri == null) - { - Console.WriteLine( - "Uri is null"); - } - - if (uri != null) - { - Console.WriteLine( - $"Uri is: {uri}"); - } + Console.WriteLine( + $"Uri is: {uri}"); + } + else + { + Console.WriteLine( + "Uri is null"); + } + } + public static void EqualityInEqualityCheckForNull(string? uri = null) + { + // 3. + if (uri == null) + { + Console.WriteLine( + "Uri is null"); + } + if (uri != null) + { + Console.WriteLine( + $"Uri is: {uri}"); } + + } #pragma warning disable IDE0150 // Prefer 'null' check over type check - public static void IsObject(string? uri = null!) + public static void IsObject(string? uri = null!) + { + // 4. + int number = 0; + if ((uri is object) + // Warning CS0183: The given + // expression is always not + // null. + && (number is object) + ) + { + Console.WriteLine( + $"Uri is: {uri}"); + } + else { - // 4. - int number = 0; - if ((uri is object) - // Warning CS0183: The given - // expression is always not - // null. - && (number is object) - ) - { - Console.WriteLine( - $"Uri is: {uri}"); - } - else - { - Console.WriteLine( - "Uri is null"); - } + Console.WriteLine( + "Uri is null"); } + } #pragma warning restore IDE0150 // Prefer 'null' check over type check - public static void IsPatternMatching(string? uri = null!) + public static void IsPatternMatching(string? uri = null!) + { + // 5. + if (uri is { }) + { + Console.WriteLine( + $"Uri is: {uri}"); + } + else { - // 5. - if (uri is { }) - { - Console.WriteLine( - $"Uri is: {uri}"); - } - else - { - Console.WriteLine( - "Uri is null"); - } + Console.WriteLine( + "Uri is null"); } + } #pragma warning disable IDE0041 // Use 'is null' check - public static void ReferenceEqualsCheckForNotNull(string? uri = null) + public static void ReferenceEqualsCheckForNotNull(string? uri = null) + { + // 6. + if (ReferenceEquals( + uri, null)) { - // 6. - if (ReferenceEquals( - uri, null)) - { - Console.WriteLine( - "Uri is null"); - } - else - { - Console.WriteLine( - $"Uri is: {uri}"); - } + Console.WriteLine( + "Uri is null"); + } + else + { + Console.WriteLine( + $"Uri is: {uri}"); } -#pragma warning restore IDE0041 // Use 'is null' check } +#pragma warning restore IDE0041 // Use 'is null' check } diff --git a/src/Chapter04/TicTacToe.cs b/src/Chapter04/TicTacToe.cs index 2f057b68b..e645cf300 100644 --- a/src/Chapter04/TicTacToe.cs +++ b/src/Chapter04/TicTacToe.cs @@ -1,240 +1,239 @@  #define CSHARP2PLUS -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.TicTacToe -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter04.TicTacToe; + +using System; #pragma warning disable 1030 // Disable user-defined warnings - // The TicTacToe class enables two players to - // play tic-tac-toe. - public class TicTacToeGame // Declares the TicTacToeGame class. +// The TicTacToe class enables two players to +// play tic-tac-toe. +public class TicTacToeGame // Declares the TicTacToeGame class. +{ + static public void Main() // Declares the entry point to the program. { - static public void Main() // Declares the entry point to the program. - { - // Stores locations each player has moved. - int[] playerPositions = { 0, 0 }; + // Stores locations each player has moved. + int[] playerPositions = { 0, 0 }; - // Initially set the currentPlayer to Player 1. - int currentPlayer = 1; + // Initially set the currentPlayer to Player 1. + int currentPlayer = 1; - // Winning player - int winner = 0; + // Winning player + int winner = 0; - string input = "Let the game begin!"; + string input = "Let the game begin!"; - // Display the board and - // prompt the current player - // for his next move. - for(int turn = 1; turn <= 10; ++turn) - { - DisplayBoard(playerPositions); + // Display the board and + // prompt the current player + // for his next move. + for(int turn = 1; turn <= 10; ++turn) + { + DisplayBoard(playerPositions); - #region Check for End Game - if(EndGame(winner, turn, input)) - { - break; - } - #endregion Check for End Game + #region Check for End Game + if(EndGame(winner, turn, input)) + { + break; + } + #endregion Check for End Game - input = NextMove(playerPositions, currentPlayer); + input = NextMove(playerPositions, currentPlayer); - winner = DetermineWinner(playerPositions); + winner = DetermineWinner(playerPositions); - // Switch players. - currentPlayer = (currentPlayer == 2) ? 1 : 2; - } + // Switch players. + currentPlayer = (currentPlayer == 2) ? 1 : 2; } + } + + private static string NextMove(int[] playerPositions, + int currentPlayer) + { + string? input; - private static string NextMove(int[] playerPositions, - int currentPlayer) + // Repeatedly prompt the player for a move + // until a valid move is entered. + bool validMove; + do { - string? input; + // Request a move from the current player. + System.Console.Write($"\nPlayer {currentPlayer} - Enter move:"); + // TODO: Update listing in Manuscript + input = System.Console.ReadLine(); + validMove = ValidateAndMove(playerPositions, + currentPlayer, input); + } while(!validMove); + + return input!; + } - // Repeatedly prompt the player for a move - // until a valid move is entered. - bool validMove; - do - { - // Request a move from the current player. - System.Console.Write($"\nPlayer {currentPlayer} - Enter move:"); - // TODO: Update listing in Manuscript - input = System.Console.ReadLine(); - validMove = ValidateAndMove(playerPositions, - currentPlayer, input); - } while(!validMove); - - return input!; + static bool EndGame(int winner, int turn, string input) + { + bool endGame = false; + if(winner > 0) + { + System.Console.WriteLine($"\nPlayer {winner} has won!!!!"); + endGame = true; } - - static bool EndGame(int winner, int turn, string input) + else if(turn == 10) { - bool endGame = false; - if(winner > 0) - { - System.Console.WriteLine($"\nPlayer {winner} has won!!!!"); - endGame = true; - } - else if(turn == 10) - { - // After completing the 10th display of the - // board, exit rather than prompting the - // user again. - System.Console.WriteLine("\nThe game was a tie!"); - endGame = true; - } - else if(input.Length == 0 || input == "quit") - { - // Check if user quit by hitting Enter without - // any characters or by typing "quit". - System.Console.WriteLine("The last player quit"); - endGame = true; - } - return endGame; + // After completing the 10th display of the + // board, exit rather than prompting the + // user again. + System.Console.WriteLine("\nThe game was a tie!"); + endGame = true; } - - static int DetermineWinner(int[] playerPositions) + else if(input.Length == 0 || input == "quit") { - int winner = 0; + // Check if user quit by hitting Enter without + // any characters or by typing "quit". + System.Console.WriteLine("The last player quit"); + endGame = true; + } + return endGame; + } + + static int DetermineWinner(int[] playerPositions) + { + int winner = 0; - // Determine if there is a winner. - int[] winningMasks = { - 7, 56, 448, 73, 146, 292, 84, 273}; + // Determine if there is a winner. + int[] winningMasks = { + 7, 56, 448, 73, 146, 292, 84, 273}; - foreach(int mask in winningMasks) + foreach(int mask in winningMasks) + { + if((mask & playerPositions[0]) == mask) + { + winner = 1; + break; + } + else if((mask & playerPositions[1]) == mask) { - if((mask & playerPositions[0]) == mask) - { - winner = 1; - break; - } - else if((mask & playerPositions[1]) == mask) - { - winner = 2; - break; - } + winner = 2; + break; } - return winner; } + return winner; + } - static bool ValidateAndMove( - int[] playerPositions, int currentPlayer, string? input) - { - bool valid = false; + static bool ValidateAndMove( + int[] playerPositions, int currentPlayer, string? input) + { + bool valid = false; - // Check the current player’s input. - switch(input) - { - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": + // Check the current player’s input. + switch(input) + { + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": #warning "Same move allowed multiple times." - int shifter; // The number of places to shift - // over to set a bit. - int position; // The bit which is to be set. - - // int.Parse() converts "input" to an integer. - // "int.Parse(input) – 1" because arrays - // are zero-based. - shifter = int.Parse(input) - 1; - - // Shift mask of 00000000000000000000000000000001 - // over by cellLocations. - position = 1 << shifter; - - // Take the current player cells and OR them - // to set the new position as well. - // Since currentPlayer is either 1 or 2 you - // subtract 1 to use currentPlayer as an - // index in a zero-based array. - playerPositions[currentPlayer - 1] |= position; - - valid = true; - break; - - case null: - case "quit": - valid = true; - break; - - case "": - default: - // If none of the other case statements - // is encountered, then the text is invalid. - System.Console.WriteLine( - "\nERROR: Enter a value from 1-9. " - + "Push ENTER to quit"); - break; - } - - return valid; + int shifter; // The number of places to shift + // over to set a bit. + int position; // The bit which is to be set. + + // int.Parse() converts "input" to an integer. + // "int.Parse(input) – 1" because arrays + // are zero-based. + shifter = int.Parse(input) - 1; + + // Shift mask of 00000000000000000000000000000001 + // over by cellLocations. + position = 1 << shifter; + + // Take the current player cells and OR them + // to set the new position as well. + // Since currentPlayer is either 1 or 2 you + // subtract 1 to use currentPlayer as an + // index in a zero-based array. + playerPositions[currentPlayer - 1] |= position; + + valid = true; + break; + + case null: + case "quit": + valid = true; + break; + + case "": + default: + // If none of the other case statements + // is encountered, then the text is invalid. + System.Console.WriteLine( + "\nERROR: Enter a value from 1-9. " + + "Push ENTER to quit"); + break; } - static void DisplayBoard(int[] playerPositions) - { - // This represents the borders between each cell - // for one row. - string[] borders = { - "|", "|", "\n---+---+---\n", "|", "|", - "\n---+---+---\n", "|", "|", "" - }; + return valid; + } + + static void DisplayBoard(int[] playerPositions) + { + // This represents the borders between each cell + // for one row. + string[] borders = { +"|", "|", "\n---+---+---\n", "|", "|", +"\n---+---+---\n", "|", "|", "" +}; - // Display the current board; - int border = 0; // set the first border (border[0] = "|"). + // Display the current board; + int border = 0; // set the first border (border[0] = "|"). #if CSHARP2PLUS - System.Console.Clear(); + System.Console.Clear(); #endif - for(int position = 1; - position <= 256; - position <<= 1, border++) - { - char token = CalculateToken( - playerPositions, position); + for(int position = 1; + position <= 256; + position <<= 1, border++) + { + char token = CalculateToken( + playerPositions, position); - // Write out a cell value and the border that - // comes after it. - System.Console.Write($" {token} {borders[border]}"); - } + // Write out a cell value and the border that + // comes after it. + System.Console.Write($" {token} {borders[border]}"); } + } - static char CalculateToken( - int[] playerPositions, int position) - { - // Initialize the players to 'X' and 'O' - char[] players = { 'X', 'O' }; + static char CalculateToken( + int[] playerPositions, int position) + { + // Initialize the players to 'X' and 'O' + char[] players = { 'X', 'O' }; - char token; - // If player has the position set, - // then set the token to that player. - if((position & playerPositions[0]) == position) - { - // Player 1 has that position marked. - token = players[0]; - } - else if((position & playerPositions[1]) == position) - { - // Player 2 has that position marked. - token = players[1]; - } - else - { - // The position is empty. - token = ' '; - } - return token; + char token; + // If player has the position set, + // then set the token to that player. + if((position & playerPositions[0]) == position) + { + // Player 1 has that position marked. + token = players[0]; + } + else if((position & playerPositions[1]) == position) + { + // Player 2 has that position marked. + token = players[1]; } + else + { + // The position is empty. + token = ' '; + } + return token; + } #line 113 "TicTacToe.cs" - // Generated code goes here. + // Generated code goes here. #line default - } } \ No newline at end of file diff --git a/src/Chapter05/Listing05.11.SpecifyingTheUsingDirectiveInsideANamespaceDeclaration.cs b/src/Chapter05/Listing05.11.SpecifyingTheUsingDirectiveInsideANamespaceDeclaration.cs index ab50973eb..69d6052c7 100644 --- a/src/Chapter05/Listing05.11.SpecifyingTheUsingDirectiveInsideANamespaceDeclaration.cs +++ b/src/Chapter05/Listing05.11.SpecifyingTheUsingDirectiveInsideANamespaceDeclaration.cs @@ -2,54 +2,53 @@ // and the attribute is not available in .NET 6.0. #pragma warning disable SYSLIB1045 // Convert to 'GeneratedRegexAttribute'. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter05.Listing05_11 -{ - #region INCLUDE - // The using directive imports all types from the - // specified namespace into the entire file - using System.Text.RegularExpressions; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter05.Listing05_11; + +#region INCLUDE +// The using directive imports all types from the +// specified namespace into the entire file +using System.Text.RegularExpressions; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region EXCLUDE - const string firstName = "FirstName"; - const string initial = "Initial"; - const string lastName = "LastName"; + #region EXCLUDE + const string firstName = "FirstName"; + const string initial = "Initial"; + const string lastName = "LastName"; - // Explaining regular expressions is beyond the - // scope of this book. - // See https://www.regular-expressions.info/ for - // more information. - const string pattern = $""" + // Explaining regular expressions is beyond the + // scope of this book. + // See https://www.regular-expressions.info/ for + // more information. + const string pattern = $""" (?<{firstName}>\w+)\s+((?<{initial}>\w)\.\s+)?(?<{lastName}>\w+)\s* """; - Console.WriteLine( - "Enter your full name (e.g. Inigo T. Montoya): "); - string name = Console.ReadLine()!; + Console.WriteLine( + "Enter your full name (e.g. Inigo T. Montoya): "); + string name = Console.ReadLine()!; - #endregion EXCLUDE - #region HIGHLIGHT - // No need to qualify RegEx type with - // System.Text.RegularExpressions because - // of the using directive above - Match match = Regex.Match(name, pattern); - #endregion HIGHLIGHT - #region EXCLUDE + #endregion EXCLUDE + #region HIGHLIGHT + // No need to qualify RegEx type with + // System.Text.RegularExpressions because + // of the using directive above + Match match = Regex.Match(name, pattern); + #endregion HIGHLIGHT + #region EXCLUDE - if (match.Success) - { - Console.WriteLine( - $"{firstName}: {match.Groups[firstName]}"); - Console.WriteLine( - $"{initial}: {match.Groups[initial]}"); - Console.WriteLine( - $"{lastName}: {match.Groups[lastName]}"); - } - #endregion EXCLUDE + if (match.Success) + { + Console.WriteLine( + $"{firstName}: {match.Groups[firstName]}"); + Console.WriteLine( + $"{initial}: {match.Groups[initial]}"); + Console.WriteLine( + $"{lastName}: {match.Groups[lastName]}"); } + #endregion EXCLUDE } } #endregion INCLUDE diff --git a/src/Chapter06/Listing06.01.DefiningAClass.cs b/src/Chapter06/Listing06.01.DefiningAClass.cs index 13512349f..104594af1 100644 --- a/src/Chapter06/Listing06.01.DefiningAClass.cs +++ b/src/Chapter06/Listing06.01.DefiningAClass.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_01; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - System.Console.WriteLine("No output in this example"); - } + System.Console.WriteLine("No output in this example"); } +} - #region INCLUDE - public class Employee - { - } - #endregion INCLUDE +#region INCLUDE +public class Employee +{ } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.02.DeclaringVariablesOfTheClassType.cs b/src/Chapter06/Listing06.02.DeclaringVariablesOfTheClassType.cs index c322740fc..be65a51c9 100644 --- a/src/Chapter06/Listing06.02.DeclaringVariablesOfTheClassType.cs +++ b/src/Chapter06/Listing06.02.DeclaringVariablesOfTheClassType.cs @@ -3,27 +3,26 @@ #pragma warning disable IDE0060 // Remove unused parameter #pragma warning disable IDE0051 // Remove unused private members -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_02 -{ - using Listing06_01; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_02; - #region INCLUDE - public class Program - { - public static void Main() - { - #region HIGHLIGHT - Employee employee1, employee2; - #endregion HIGHLIGHT - // ... - } +using Listing06_01; +#region INCLUDE +public class Program +{ + public static void Main() + { #region HIGHLIGHT - public static void IncreaseSalary(Employee employee) + Employee employee1, employee2; #endregion HIGHLIGHT - { - // ... - } + // ... + } + + #region HIGHLIGHT + public static void IncreaseSalary(Employee employee) + #endregion HIGHLIGHT + { + // ... } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.03.InstantiatingAClass.cs b/src/Chapter06/Listing06.03.InstantiatingAClass.cs index 4f2124ca5..dfe92270a 100644 --- a/src/Chapter06/Listing06.03.InstantiatingAClass.cs +++ b/src/Chapter06/Listing06.03.InstantiatingAClass.cs @@ -1,32 +1,31 @@ // Justificaiton: only partial implementation provided for elucidation. #pragma warning disable IDE0060 // Remove unused parameter -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_03 -{ - using Listing06_01; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_03; + +using Listing06_01; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - #region HIGHLIGHT - Employee employee1 = new Employee(); - #endregion HIGHLIGHT - Employee employee2; - #region HIGHLIGHT - employee2 = new(); - #endregion HIGHLIGHT + #region HIGHLIGHT + Employee employee1 = new Employee(); + #endregion HIGHLIGHT + Employee employee2; + #region HIGHLIGHT + employee2 = new(); + #endregion HIGHLIGHT - IncreaseSalary(employee1); - IncreaseSalary(employee2); - } - #region EXCLUDE - public static void IncreaseSalary(Employee employee) - { - // ... - } - #endregion EXCLUDE + IncreaseSalary(employee1); + IncreaseSalary(employee2); + } + #region EXCLUDE + public static void IncreaseSalary(Employee employee) + { + // ... } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.04.DeclaringFields.cs b/src/Chapter06/Listing06.04.DeclaringFields.cs index 22c792481..4f3ad9a0d 100644 --- a/src/Chapter06/Listing06.04.DeclaringFields.cs +++ b/src/Chapter06/Listing06.04.DeclaringFields.cs @@ -1,14 +1,13 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_04; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; - } - #endregion INCLUDE + public string FirstName; + public string LastName; + public string? Salary; } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.05.SettingInitialValuesOfFieldsAtDeclarationTime.cs b/src/Chapter06/Listing06.05.SettingInitialValuesOfFieldsAtDeclarationTime.cs index 11c9a787f..57d9c9aaa 100644 --- a/src/Chapter06/Listing06.05.SettingInitialValuesOfFieldsAtDeclarationTime.cs +++ b/src/Chapter06/Listing06.05.SettingInitialValuesOfFieldsAtDeclarationTime.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_05; + +#region INCLUDE +// Non-nullable field uninitialized warning disabled while code is incomplete +#pragma warning disable CS8618 +public class Employee { - #region INCLUDE - // Non-nullable field uninitialized warning disabled while code is incomplete - #pragma warning disable CS8618 - public class Employee - { - public string FirstName; - public string LastName; - #region HIGHLIGHT - public string? Salary = "Not enough"; - #endregion HIGHLIGHT - } - #endregion INCLUDE + public string FirstName; + public string LastName; + #region HIGHLIGHT + public string? Salary = "Not enough"; + #endregion HIGHLIGHT } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.06.AccessingFields.cs b/src/Chapter06/Listing06.06.AccessingFields.cs index 3b3875867..7bc5c8a6d 100644 --- a/src/Chapter06/Listing06.06.AccessingFields.cs +++ b/src/Chapter06/Listing06.06.AccessingFields.cs @@ -1,37 +1,36 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_06 -{ - using Listing06_05; - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_06; + +using Listing06_05; +using System; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee1 = new(); - Employee employee2; - employee2 = new Employee(); + Employee employee1 = new(); + Employee employee2; + employee2 = new Employee(); - #region HIGHLIGHT - employee1.FirstName = "Inigo"; - employee1.LastName = "Montoya"; - employee1.Salary = "Too Little"; - IncreaseSalary(employee1); - Console.WriteLine( - "{0} {1}: {2}", - employee1.FirstName, - employee1.LastName, - employee1.Salary); - #endregion HIGHLIGHT - // ... - } + #region HIGHLIGHT + employee1.FirstName = "Inigo"; + employee1.LastName = "Montoya"; + employee1.Salary = "Too Little"; + IncreaseSalary(employee1); + Console.WriteLine( + "{0} {1}: {2}", + employee1.FirstName, + employee1.LastName, + employee1.Salary); + #endregion HIGHLIGHT + // ... + } - public static void IncreaseSalary(Employee employee) - { - #region HIGHLIGHT - employee.Salary = "Enough to survive on"; - #endregion HIGHLIGHT - } + public static void IncreaseSalary(Employee employee) + { + #region HIGHLIGHT + employee.Salary = "Enough to survive on"; + #endregion HIGHLIGHT } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.07.AccessingFieldsFromWithinTheContainingClass.cs b/src/Chapter06/Listing06.07.AccessingFieldsFromWithinTheContainingClass.cs index 100a89301..7a7196310 100644 --- a/src/Chapter06/Listing06.07.AccessingFieldsFromWithinTheContainingClass.cs +++ b/src/Chapter06/Listing06.07.AccessingFieldsFromWithinTheContainingClass.cs @@ -1,21 +1,20 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_07; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; + public string FirstName; + public string LastName; + public string? Salary; - #region HIGHLIGHT - public string GetName() - { - return $"{ FirstName } { LastName }"; - } - #endregion HIGHLIGHT + #region HIGHLIGHT + public string GetName() + { + return $"{ FirstName } { LastName }"; } - #endregion INCLUDE + #endregion HIGHLIGHT } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.08.AccessingFieldsFromOutsideTheContainingClass.cs b/src/Chapter06/Listing06.08.AccessingFieldsFromOutsideTheContainingClass.cs index 795ddd5c3..aa88b1b26 100644 --- a/src/Chapter06/Listing06.08.AccessingFieldsFromOutsideTheContainingClass.cs +++ b/src/Chapter06/Listing06.08.AccessingFieldsFromOutsideTheContainingClass.cs @@ -3,47 +3,46 @@ // Unnecessary assignment of a value #pragma warning disable IDE0059 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_08 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_08; + +using System; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee1 = new Employee(); - Employee employee2; - employee2 = new(); + Employee employee1 = new Employee(); + Employee employee2; + employee2 = new(); - employee1.FirstName = "Inigo"; - employee1.LastName = "Montoya"; - employee1.Salary = "Too Little"; - IncreaseSalary(employee1); - #region HIGHLIGHT - Console.WriteLine( - $"{ employee1.GetName() }: { employee1.Salary }"); - #endregion HIGHLIGHT - // ... - } - #region EXCLUDE - public static void IncreaseSalary(Employee employee) - { - employee.Salary = "Enough to survive on"; - } + employee1.FirstName = "Inigo"; + employee1.LastName = "Montoya"; + employee1.Salary = "Too Little"; + IncreaseSalary(employee1); + #region HIGHLIGHT + Console.WriteLine( + $"{ employee1.GetName() }: { employee1.Salary }"); + #endregion HIGHLIGHT + // ... } - - public class Employee + #region EXCLUDE + public static void IncreaseSalary(Employee employee) { - public string FirstName; - public string LastName; - public string? Salary = "Not enough"; + employee.Salary = "Enough to survive on"; + } +} + +public class Employee +{ + public string FirstName; + public string LastName; + public string? Salary = "Not enough"; - public string GetName() - { - return FirstName + " " + LastName; - } - #endregion EXCLUDE + public string GetName() + { + return FirstName + " " + LastName; } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.09.UsingThisToIdentifyTheFieldsOwnerExplicitly.cs b/src/Chapter06/Listing06.09.UsingThisToIdentifyTheFieldsOwnerExplicitly.cs index 254c999ed..e009aa8f9 100644 --- a/src/Chapter06/Listing06.09.UsingThisToIdentifyTheFieldsOwnerExplicitly.cs +++ b/src/Chapter06/Listing06.09.UsingThisToIdentifyTheFieldsOwnerExplicitly.cs @@ -1,28 +1,27 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_09; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; + public string FirstName; + public string LastName; + public string? Salary; - public string GetName() - { - return $"{ FirstName } { LastName }"; - } + public string GetName() + { + return $"{ FirstName } { LastName }"; + } - #region HIGHLIGHT - public void SetName( - string newFirstName, string newLastName) - { - this.FirstName = newFirstName; - this.LastName = newLastName; - } - #endregion HIGHLIGHT + #region HIGHLIGHT + public void SetName( + string newFirstName, string newLastName) + { + this.FirstName = newFirstName; + this.LastName = newLastName; } - #endregion INCLUDE + #endregion HIGHLIGHT } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.10.UsingThisToAvoidAmbiguity.cs b/src/Chapter06/Listing06.10.UsingThisToAvoidAmbiguity.cs index 7c6e05cd9..0d9f576e6 100644 --- a/src/Chapter06/Listing06.10.UsingThisToAvoidAmbiguity.cs +++ b/src/Chapter06/Listing06.10.UsingThisToAvoidAmbiguity.cs @@ -1,26 +1,25 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_10; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; + public string FirstName; + public string LastName; + public string? Salary; - public string GetName() - { - return $"{ FirstName } { LastName }"; - } + public string GetName() + { + return $"{ FirstName } { LastName }"; + } - // Caution: Parameter names use PascalCase - public void SetName(string FirstName, string LastName) - { - this.FirstName = FirstName; - this.LastName = LastName; - } + // Caution: Parameter names use PascalCase + public void SetName(string FirstName, string LastName) + { + this.FirstName = FirstName; + this.LastName = LastName; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.11.UsingThisWithAMethod.cs b/src/Chapter06/Listing06.11.UsingThisWithAMethod.cs index 2eaca1e0d..0a6b2262a 100644 --- a/src/Chapter06/Listing06.11.UsingThisWithAMethod.cs +++ b/src/Chapter06/Listing06.11.UsingThisWithAMethod.cs @@ -1,45 +1,44 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_11; + +using System; + +#region INCLUDE +public class Employee { - using System; + #region EXCLUDE + public string FirstName; + public string LastName; + public string? Salary = "Not enough"; + #endregion EXCLUDE - #region INCLUDE - public class Employee + public string GetName() { - #region EXCLUDE - public string FirstName; - public string LastName; - public string? Salary = "Not enough"; - #endregion EXCLUDE - - public string GetName() - { - return $"{ FirstName } { LastName }"; - } + return $"{ FirstName } { LastName }"; + } - public void SetName(string newFirstName, string newLastName) - { - this.FirstName = newFirstName; - this.LastName = newLastName; - #region HIGHLIGHT - Console.WriteLine( - $"Name changed to '{ this.GetName() }'"); - #endregion HIGHLIGHT - } + public void SetName(string newFirstName, string newLastName) + { + this.FirstName = newFirstName; + this.LastName = newLastName; + #region HIGHLIGHT + Console.WriteLine( + $"Name changed to '{ this.GetName() }'"); + #endregion HIGHLIGHT } +} - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee = new(); + Employee employee = new(); - employee.SetName("Inigo", "Montoya"); - // ... - } + employee.SetName("Inigo", "Montoya"); // ... } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.12.PassingThisInAMethodCall.cs b/src/Chapter06/Listing06.12.PassingThisInAMethodCall.cs index 877ebde8f..4bab229bc 100644 --- a/src/Chapter06/Listing06.12.PassingThisInAMethodCall.cs +++ b/src/Chapter06/Listing06.12.PassingThisInAMethodCall.cs @@ -1,36 +1,35 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_12; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; + public string FirstName; + public string LastName; + public string? Salary; - public void Save() - { - #region HIGHLIGHT - DataStorage.Store(this); - #endregion HIGHLIGHT - } + public void Save() + { + #region HIGHLIGHT + DataStorage.Store(this); + #endregion HIGHLIGHT } +} - public class DataStorage +public class DataStorage +{ + // Save an employee object to a file + // named with the Employee name + public static void Store(Employee employee) { - // Save an employee object to a file - // named with the Employee name - public static void Store(Employee employee) - { - #region EXCLUDE - System.Diagnostics.Trace.WriteLine( - $@"Writing employee ({ - employee.FirstName} {employee.LastName - }) information to file."); - #endregion EXCLUDE - } + #region EXCLUDE + System.Diagnostics.Trace.WriteLine( + $@"Writing employee ({ + employee.FirstName} {employee.LastName + }) information to file."); + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.13.DataPersistenceToAFile.cs b/src/Chapter06/Listing06.13.DataPersistenceToAFile.cs index 9ef6c73eb..3b35165bb 100644 --- a/src/Chapter06/Listing06.13.DataPersistenceToAFile.cs +++ b/src/Chapter06/Listing06.13.DataPersistenceToAFile.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_13; + +using Listing06_12; +#region INCLUDE +public class DataStorage { - using Listing06_12; - #region INCLUDE - public class DataStorage + // Save an employee object to a file + // named with the Employee name + // Error handling not shown + public static void Store(Employee employee) { - // Save an employee object to a file - // named with the Employee name - // Error handling not shown - public static void Store(Employee employee) - { - // Instantiate a FileStream using FirstNameLastName.dat - // for the filename. FileMode.Create will force - // a new file to be created or override an - // existing file - // Note: This code could be improved with a using - // statement — a construct that we have avoided because - // it has not yet been introduced. - FileStream stream = new( - employee.FirstName + employee.LastName + ".dat", - FileMode.Create); + // Instantiate a FileStream using FirstNameLastName.dat + // for the filename. FileMode.Create will force + // a new file to be created or override an + // existing file + // Note: This code could be improved with a using + // statement — a construct that we have avoided because + // it has not yet been introduced. + FileStream stream = new( + employee.FirstName + employee.LastName + ".dat", + FileMode.Create); - // Create a StreamWriter object for writing text - // into the FileStream - StreamWriter writer = new(stream); + // Create a StreamWriter object for writing text + // into the FileStream + StreamWriter writer = new(stream); - // Write all the data associated with the employee - writer.WriteLine(employee.FirstName); - writer.WriteLine(employee.LastName); - writer.WriteLine(employee.Salary); + // Write all the data associated with the employee + writer.WriteLine(employee.FirstName); + writer.WriteLine(employee.LastName); + writer.WriteLine(employee.Salary); - // Dispose the StreamWriter and its stream - writer.Dispose(); // Automatically closes the stream - } - // ... + // Dispose the StreamWriter and its stream + writer.Dispose(); // Automatically closes the stream } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.14.DataRetrievalFromAFile.cs b/src/Chapter06/Listing06.14.DataRetrievalFromAFile.cs index 7ad18f73e..761319a7f 100644 --- a/src/Chapter06/Listing06.14.DataRetrievalFromAFile.cs +++ b/src/Chapter06/Listing06.14.DataRetrievalFromAFile.cs @@ -1,128 +1,127 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_14; + +#region INCLUDE +using System; +// IO namespace +using System.IO; + +public class Employee { - #region INCLUDE - using System; - // IO namespace - using System.IO; + #region EXCLUDE + public string FirstName; + public string LastName; + public string? Salary; + + public string GetName() + { + return $"{ FirstName } { LastName }"; + } - public class Employee + public void SetName(string newFirstName, string newLastName) { - #region EXCLUDE - public string FirstName; - public string LastName; - public string? Salary; - - public string GetName() - { - return $"{ FirstName } { LastName }"; - } - - public void SetName(string newFirstName, string newLastName) - { - this.FirstName = newFirstName; - this.LastName = newLastName; - Console.WriteLine( - $"Name changed to '{ this.GetName() }'"); - } - - public void Save() - { - DataStorage.Store(this); - } - #endregion EXCLUDE + this.FirstName = newFirstName; + this.LastName = newLastName; + Console.WriteLine( + $"Name changed to '{ this.GetName() }'"); } - public class DataStorage + public void Save() { - #region EXCLUDE - // Save an employee object to a file - // named with the Employee name - // Error handling not shown - public static void Store(Employee employee) - { - // Instantiate a FileStream using FirstNameLastName.dat - // for the filename. FileMode.Create will force - // a new file to be created or override an - // existing file. - // Note: This code could be improved with a using - // statement — a construct that we have avoided because - // it has not yet been introduced. - FileStream stream = new( - employee.FirstName + employee.LastName + ".dat", - FileMode.Create); - - // Create a StreamWriter object for writing text - // into the FileStream - StreamWriter writer = new(stream); - - // Write all the data associated with the employee - writer.WriteLine(employee.FirstName); - writer.WriteLine(employee.LastName); - writer.WriteLine(employee.Salary); - - // Dispose the StreamWriter and its stream - writer.Dispose(); // Automatically closes the stream - } - #endregion EXCLUDE - - public static Employee Load(string firstName, string lastName) - { - Employee employee = new(); - - // Instantiate a FileStream using FirstNameLastName.dat - // for the filename. FileMode.Open will open - // an existing file or else report an error - FileStream stream = new( - firstName + lastName + ".dat", FileMode.Open); - - // Create a StreamReader for reading text from the file - StreamReader reader = new(stream); - - // Read each line from the file and place it into - // the associated property. - employee.FirstName = reader.ReadLine()?? - throw new InvalidOperationException( - "FirstName cannot be null"); - employee.LastName = reader.ReadLine()?? - throw new InvalidOperationException( - "LastName cannot be null"); - employee.Salary = reader.ReadLine(); - - // Dispose the StreamReader and its Stream - reader.Dispose(); // Automatically closes the stream - - return employee; - } + DataStorage.Store(this); } + #endregion EXCLUDE +} - public class Program +public class DataStorage +{ + #region EXCLUDE + // Save an employee object to a file + // named with the Employee name + // Error handling not shown + public static void Store(Employee employee) + { + // Instantiate a FileStream using FirstNameLastName.dat + // for the filename. FileMode.Create will force + // a new file to be created or override an + // existing file. + // Note: This code could be improved with a using + // statement — a construct that we have avoided because + // it has not yet been introduced. + FileStream stream = new( + employee.FirstName + employee.LastName + ".dat", + FileMode.Create); + + // Create a StreamWriter object for writing text + // into the FileStream + StreamWriter writer = new(stream); + + // Write all the data associated with the employee + writer.WriteLine(employee.FirstName); + writer.WriteLine(employee.LastName); + writer.WriteLine(employee.Salary); + + // Dispose the StreamWriter and its stream + writer.Dispose(); // Automatically closes the stream + } + #endregion EXCLUDE + + public static Employee Load(string firstName, string lastName) + { + Employee employee = new(); + + // Instantiate a FileStream using FirstNameLastName.dat + // for the filename. FileMode.Open will open + // an existing file or else report an error + FileStream stream = new( + firstName + lastName + ".dat", FileMode.Open); + + // Create a StreamReader for reading text from the file + StreamReader reader = new(stream); + + // Read each line from the file and place it into + // the associated property. + employee.FirstName = reader.ReadLine()?? + throw new InvalidOperationException( + "FirstName cannot be null"); + employee.LastName = reader.ReadLine()?? + throw new InvalidOperationException( + "LastName cannot be null"); + employee.Salary = reader.ReadLine(); + + // Dispose the StreamReader and its Stream + reader.Dispose(); // Automatically closes the stream + + return employee; + } +} + +public class Program +{ + public static void Main() + { + Employee employee1; + + Employee employee2 = new(); + employee2.SetName("Inigo", "Montoya"); + employee2.Save(); + + // Modify employee2 after saving + IncreaseSalary(employee2); + + // Load employee1 from the saved version of employee2 + employee1 = DataStorage.Load("Inigo", "Montoya"); + + Console.WriteLine( + $"{ employee1.GetName() }: { employee1.Salary }"); + } + #region EXCLUDE + public static void IncreaseSalary(Employee employee) { - public static void Main() - { - Employee employee1; - - Employee employee2 = new(); - employee2.SetName("Inigo", "Montoya"); - employee2.Save(); - - // Modify employee2 after saving - IncreaseSalary(employee2); - - // Load employee1 from the saved version of employee2 - employee1 = DataStorage.Load("Inigo", "Montoya"); - - Console.WriteLine( - $"{ employee1.GetName() }: { employee1.Salary }"); - } - #region EXCLUDE - public static void IncreaseSalary(Employee employee) - { - employee.Salary = "Enough to survive on"; - } - #endregion EXCLUDE + employee.Salary = "Enough to survive on"; } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.15.UsingThePrivateAccessModifier.cs b/src/Chapter06/Listing06.15.UsingThePrivateAccessModifier.cs index 4fe4896a4..0f4aea7ad 100644 --- a/src/Chapter06/Listing06.15.UsingThePrivateAccessModifier.cs +++ b/src/Chapter06/Listing06.15.UsingThePrivateAccessModifier.cs @@ -8,62 +8,61 @@ #pragma warning disable IDE0044 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_15 -{ - #region INCLUDE - public class Employee - { - public string FirstName; - public string LastName; - public string? Salary; - // Working de-crypted passwords for elucidation only - // this is not recommended. - // Uninitialized; pending explanation of constructors - #region HIGHLIGHT - private string Password; - private bool IsAuthenticated; - #endregion HIGHLIGHT +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_15; - #region HIGHLIGHT - public bool Logon(string password) - { - if(Password == password) - { - IsAuthenticated = true; - } - return IsAuthenticated; - } +#region INCLUDE +public class Employee +{ + public string FirstName; + public string LastName; + public string? Salary; + // Working de-crypted passwords for elucidation only + // this is not recommended. + // Uninitialized; pending explanation of constructors + #region HIGHLIGHT + private string Password; + private bool IsAuthenticated; + #endregion HIGHLIGHT - public bool GetIsAuthenticated() + #region HIGHLIGHT + public bool Logon(string password) + { + if(Password == password) { - return IsAuthenticated; + IsAuthenticated = true; } - #endregion HIGHLIGHT - // ... + return IsAuthenticated; } - public class Program + public bool GetIsAuthenticated() { - public static void Main() - { - Employee employee = new(); + return IsAuthenticated; + } + #endregion HIGHLIGHT + // ... +} - employee.FirstName = "Inigo"; - employee.LastName = "Montoya"; +public class Program +{ + public static void Main() + { + Employee employee = new(); - // ... + employee.FirstName = "Inigo"; + employee.LastName = "Montoya"; - - #if COMPILEERROR // EXCLUDE - #region HIGHLIGHT - // ERROR: Password is private, so it cannot be - // accessed from outside the class - Console.WriteLine( - "Password = {0}", employee.Password); - #endregion HIGHLIGHT - #endif // COMPILEERROR // EXCLUDE - } // ... + + + #if COMPILEERROR // EXCLUDE + #region HIGHLIGHT + // ERROR: Password is private, so it cannot be + // accessed from outside the class + Console.WriteLine( + "Password = {0}", employee.Password); + #endregion HIGHLIGHT + #endif // COMPILEERROR // EXCLUDE } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.16.GettersAndSetters.cs b/src/Chapter06/Listing06.16.GettersAndSetters.cs index 38fd6d891..02f7c2044 100644 --- a/src/Chapter06/Listing06.16.GettersAndSetters.cs +++ b/src/Chapter06/Listing06.16.GettersAndSetters.cs @@ -1,41 +1,40 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_16; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + private string FirstName; + // FirstName getter + public string GetFirstName() { - private string FirstName; - // FirstName getter - public string GetFirstName() - { - return FirstName; - } - // FirstName setter - public void SetFirstName(string newFirstName) + return FirstName; + } + // FirstName setter + public void SetFirstName(string newFirstName) + { + if(newFirstName != null && newFirstName != "") { - if(newFirstName != null && newFirstName != "") - { - FirstName = newFirstName; - } + FirstName = newFirstName; } + } - private string LastName; - // LastName getter - public string GetLastName() - { - return LastName; - } - // LastName setter - public void SetLastName(string newLastName) + private string LastName; + // LastName getter + public string GetLastName() + { + return LastName; + } + // LastName setter + public void SetLastName(string newLastName) + { + if(newLastName != null && newLastName != "") { - if(newLastName != null && newLastName != "") - { - LastName = newLastName; - } + LastName = newLastName; } - // ... } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.17.DefiningProperties.cs b/src/Chapter06/Listing06.17.DefiningProperties.cs index 3ce1f4d3e..3f849140b 100644 --- a/src/Chapter06/Listing06.17.DefiningProperties.cs +++ b/src/Chapter06/Listing06.17.DefiningProperties.cs @@ -3,42 +3,41 @@ // Disabled pending introductin to object initializers #pragma warning disable IDE0017 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_17; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee = new(); + Employee employee = new(); - // Call the FirstName property's setter - employee.FirstName = "Inigo"; + // Call the FirstName property's setter + employee.FirstName = "Inigo"; - // Call the FirstName property's getter - System.Console.WriteLine(employee.FirstName); - } + // Call the FirstName property's getter + System.Console.WriteLine(employee.FirstName); } +} - public class Employee +public class Employee +{ + #region HIGHLIGHT + // FirstName property + public string FirstName { - #region HIGHLIGHT - // FirstName property - public string FirstName + get { - get - { - return _FirstName; - } - set - { - _FirstName = value; - } + return _FirstName; + } + set + { + _FirstName = value; } - private string _FirstName; - #endregion HIGHLIGHT - - // ... } - #endregion INCLUDE + private string _FirstName; + #endregion HIGHLIGHT + + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.18.DefiningPropertiesWithExpressionBodiedMembers.cs b/src/Chapter06/Listing06.18.DefiningPropertiesWithExpressionBodiedMembers.cs index 0d552e567..b3e1b96f0 100644 --- a/src/Chapter06/Listing06.18.DefiningPropertiesWithExpressionBodiedMembers.cs +++ b/src/Chapter06/Listing06.18.DefiningPropertiesWithExpressionBodiedMembers.cs @@ -3,48 +3,47 @@ // Disabled pending introductin to object initializers #pragma warning disable IDE0017 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_18; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - Employee employee = new(); + Employee employee = new(); - // Call the FirstName property's setter - employee.FirstName = "Inigo"; + // Call the FirstName property's setter + employee.FirstName = "Inigo"; - // Call the FirstName property's getter - System.Console.WriteLine(employee.FirstName); - } + // Call the FirstName property's getter + System.Console.WriteLine(employee.FirstName); } +} - #region INCLUDE - public class Employee +#region INCLUDE +public class Employee +{ + // FirstName property + public string FirstName { - // FirstName property - public string FirstName + get { - get - { - return _FirstName; - } - set - { - _FirstName = value; - } + return _FirstName; } - #region HIGHLIGHT - private string _FirstName; - // LastName property - public string LastName + set { - get => _LastName; - set => _LastName = value; + _FirstName = value; } - private string _LastName; - #endregion HIGHLIGHT - // ... } - #endregion INCLUDE + #region HIGHLIGHT + private string _FirstName; + // LastName property + public string LastName + { + get => _LastName; + set => _LastName = value; + } + private string _LastName; + #endregion HIGHLIGHT + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.19.AutomaticallyImplementedProperties.cs b/src/Chapter06/Listing06.19.AutomaticallyImplementedProperties.cs index e37b67c65..ae52d37c4 100644 --- a/src/Chapter06/Listing06.19.AutomaticallyImplementedProperties.cs +++ b/src/Chapter06/Listing06.19.AutomaticallyImplementedProperties.cs @@ -1,71 +1,70 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_19; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee1 = - new(); - Employee employee2 = - new(); + Employee employee1 = + new(); + Employee employee2 = + new(); - // Call the FirstName property's setter - employee1.FirstName = "Inigo"; + // Call the FirstName property's setter + employee1.FirstName = "Inigo"; - // Call the FirstName property's getter - System.Console.WriteLine(employee1.FirstName); + // Call the FirstName property's getter + System.Console.WriteLine(employee1.FirstName); - // Assign an auto-implemented property - employee2.Title = "Computer Nerd"; - employee1.Manager = employee2; + // Assign an auto-implemented property + employee2.Title = "Computer Nerd"; + employee1.Manager = employee2; - // Print employee1's manager's title - System.Console.WriteLine(employee1.Manager.Title); - } + // Print employee1's manager's title + System.Console.WriteLine(employee1.Manager.Title); } +} - public class Employee +public class Employee +{ + // FirstName property + public string FirstName { - // FirstName property - public string FirstName + get { - get - { - return _FirstName; - } - set - { - _FirstName = value; - } + return _FirstName; } - private string _FirstName; - - // LastName property - public string LastName + set { - get => _LastName; - set => _LastName = value; + _FirstName = value; } - private string _LastName; + } + private string _FirstName; - #region HIGHLIGHT - // Title property - public string? Title { get; set; } - #endregion HIGHLIGHT + // LastName property + public string LastName + { + get => _LastName; + set => _LastName = value; + } + private string _LastName; - #region HIGHLIGHT - // Manager property - public Employee? Manager { get; set; } - #endregion HIGHLIGHT + #region HIGHLIGHT + // Title property + public string? Title { get; set; } + #endregion HIGHLIGHT - #region HIGHLIGHT - public string? Salary { get; set; } = "Not Enough"; - #endregion HIGHLIGHT - // ... - } - #endregion INCLUDE + #region HIGHLIGHT + // Manager property + public Employee? Manager { get; set; } + #endregion HIGHLIGHT + + #region HIGHLIGHT + public string? Salary { get; set; } = "Not Enough"; + #endregion HIGHLIGHT + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.20.ProvidingPropertyValidation.cs b/src/Chapter06/Listing06.20.ProvidingPropertyValidation.cs index c52c1e722..fc3105a6e 100644 --- a/src/Chapter06/Listing06.20.ProvidingPropertyValidation.cs +++ b/src/Chapter06/Listing06.20.ProvidingPropertyValidation.cs @@ -2,79 +2,78 @@ #pragma warning disable CS8618 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_20; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + // ... + public void Initialize( + string newFirstName, string newLastName) { - // ... - public void Initialize( - string newFirstName, string newLastName) - { - // Use property inside the Employee - // class as well - FirstName = newFirstName; - LastName = newLastName; - } + // Use property inside the Employee + // class as well + FirstName = newFirstName; + LastName = newLastName; + } - // LastName property - public string LastName + // LastName property + public string LastName + { + get => _LastName; + set { - get => _LastName; - set - { - // #region EXCLUDE + // #region EXCLUDE #if !NET7_0_OR_GREATER - // Validate LastName assignment - value = value?.Trim() ?? throw new ArgumentNullException(nameof(value)); - if(value.Length == 0) - { - // Report error - throw new ArgumentException( - "LastName cannot be blank or whitespace.", nameof(value)); - } -#else - // #endregion EXCLUDE - #region HIGHLIGHT - // Validate LastName assignment - - ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); - #endregion HIGHLIGHT - // #region EXCLUDE - #endif // NET7_0_OR_GREATER - // #endregion EXCLUDE - _LastName = value; + // Validate LastName assignment + value = value?.Trim() ?? throw new ArgumentNullException(nameof(value)); + if(value.Length == 0) + { + // Report error + throw new ArgumentException( + "LastName cannot be blank or whitespace.", nameof(value)); } +#else + // #endregion EXCLUDE + #region HIGHLIGHT + // Validate LastName assignment + + ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); + #endregion HIGHLIGHT + // #region EXCLUDE + #endif // NET7_0_OR_GREATER + // #endregion EXCLUDE + _LastName = value; } - private string _LastName; + } + private string _LastName; #region EXCLUDE - // FirstName property - public string FirstName + // FirstName property + public string FirstName + { + get { - get - { - return _FirstName; - } - set + return _FirstName; + } + set + { + #if !NET7_0_OR_GREATER + // Validate FirstName assignment + value = value?.Trim() ?? throw new ArgumentNullException(nameof(value)); + if (value.Length == 0) { - #if !NET7_0_OR_GREATER - // Validate FirstName assignment - value = value?.Trim() ?? throw new ArgumentNullException(nameof(value)); - if (value.Length == 0) - { - // Report error - throw new ArgumentException( - "LastName cannot be blank or whitespace.", nameof(value)); - } - #else // NET7_0_OR_GREATER - // Validate LastName assignment - ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); - #endif // NET7_0_OR_GREATER - _FirstName = value; + // Report error + throw new ArgumentException( + "LastName cannot be blank or whitespace.", nameof(value)); } + #else // NET7_0_OR_GREATER + // Validate LastName assignment + ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); + #endif // NET7_0_OR_GREATER + _FirstName = value; } - private string _FirstName; -#endregion EXCLUDE } -#endregion INCLUDE + private string _FirstName; +#endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.21.DefiningReadOnlyProperties.cs b/src/Chapter06/Listing06.21.DefiningReadOnlyProperties.cs index ae01d702d..ceeac742d 100644 --- a/src/Chapter06/Listing06.21.DefiningReadOnlyProperties.cs +++ b/src/Chapter06/Listing06.21.DefiningReadOnlyProperties.cs @@ -1,47 +1,46 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 // Pending a constructors -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_21; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee1 = new(); - employee1.Initialize(42); + Employee employee1 = new(); + employee1.Initialize(42); - #if COMPILEERROR // EXCLUDE - #region HIGHLIGHT - // ERROR: Property or indexer 'Employee.Id' - // cannot be assigned to; it is read-only - employee1.Id = "490"; - #endregion HIGHLIGHT - #endif // COMPILEERROR // EXCLUDE - } + #if COMPILEERROR // EXCLUDE + #region HIGHLIGHT + // ERROR: Property or indexer 'Employee.Id' + // cannot be assigned to; it is read-only + employee1.Id = "490"; + #endregion HIGHLIGHT + #endif // COMPILEERROR // EXCLUDE } +} - public class Employee +public class Employee +{ + public void Initialize(int id) { - public void Initialize(int id) - { - #region HIGHLIGHT - // Use field because Id property has no setter; - // it is read-only - _Id = id.ToString(); - #endregion HIGHLIGHT - } + #region HIGHLIGHT + // Use field because Id property has no setter; + // it is read-only + _Id = id.ToString(); + #endregion HIGHLIGHT + } - // ... - // Id property declaration - public string Id - { - get => _Id; - #region HIGHLIGHT - // No setter provided - #endregion HIGHLIGHT - } - private string _Id; + // ... + // Id property declaration + public string Id + { + get => _Id; + #region HIGHLIGHT + // No setter provided + #endregion HIGHLIGHT } - #endregion INCLUDE + private string _Id; } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.22.DefiningCalculatedProperties.cs b/src/Chapter06/Listing06.22.DefiningCalculatedProperties.cs index 3341ffb48..6abbffb48 100644 --- a/src/Chapter06/Listing06.22.DefiningCalculatedProperties.cs +++ b/src/Chapter06/Listing06.22.DefiningCalculatedProperties.cs @@ -3,100 +3,99 @@ // Disabled pending introductin to object initializers #pragma warning disable IDE0017 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_22; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee1 = new(); + Employee employee1 = new(); - #region HIGHLIGHT - employee1.Name = "Inigo Montoya"; - System.Console.WriteLine(employee1.Name); - #endregion HIGHLIGHT + #region HIGHLIGHT + employee1.Name = "Inigo Montoya"; + System.Console.WriteLine(employee1.Name); + #endregion HIGHLIGHT - // ... - } + // ... } +} - public class Employee - { - // ... +public class Employee +{ + // ... - // FirstName property - public string FirstName + // FirstName property + public string FirstName + { + get { - get - { - return _FirstName; - } - set - { - _FirstName = value; - } + return _FirstName; } - private string _FirstName; - - // LastName property - public string LastName + set { - get => _LastName; - set => _LastName = value; + _FirstName = value; } - private string _LastName; - // ... + } + private string _FirstName; - #region HIGHLIGHT - // Name property - public string Name + // LastName property + public string LastName + { + get => _LastName; + set => _LastName = value; + } + private string _LastName; + // ... + + #region HIGHLIGHT + // Name property + public string Name + { + get { - get - { - return $"{ FirstName } { LastName }"; - } - set - { - // #region EXCLUDE + return $"{ FirstName } { LastName }"; + } + set + { + // #region EXCLUDE #if !NET7_0_OR_GREATER - value = value?.Trim() ?? - throw new ArgumentException("Value cannot be null, empty or Whitespace"); + value = value?.Trim() ?? + throw new ArgumentException("Value cannot be null, empty or Whitespace"); #else - // #endregion EXCLUDE - ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); - // #region EXCLUDE + // #endregion EXCLUDE + ArgumentException.ThrowIfNullOrEmpty(value = value?.Trim()!); + // #region EXCLUDE #endif // NET7_0_OR_GREATER - // #endregion EXCLUDE - // Split the assigned value into - // first and last names - string[] names; - names = value.Split(new char[] { ' ' }); - if(names.Length == 2) - { - FirstName = names[0]; - LastName = names[1]; - } - else - { - // Throw an exception if the full - // name was not assigned - throw new System.ArgumentException( - $"Assigned value '{ value }' is invalid", - nameof(value)); - } + // #endregion EXCLUDE + // Split the assigned value into + // first and last names + string[] names; + names = value.Split(new char[] { ' ' }); + if(names.Length == 2) + { + FirstName = names[0]; + LastName = names[1]; + } + else + { + // Throw an exception if the full + // name was not assigned + throw new System.ArgumentException( + $"Assigned value '{ value }' is invalid", + nameof(value)); } } - #endregion HIGHLIGHT + } + #endregion HIGHLIGHT - public string Initials => $"{ FirstName[0] } { LastName[0] }"; - #region EXCLUDE - // Title property - public string? Title { get; set; } + public string Initials => $"{ FirstName[0] } { LastName[0] }"; + #region EXCLUDE + // Title property + public string? Title { get; set; } - // Manager property - public Employee? Manager { get; set; } - #endregion EXCLUDE - } - #endregion INCLUDE + // Manager property + public Employee? Manager { get; set; } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.23.PlacingAccessModifiersOnSetters.cs b/src/Chapter06/Listing06.23.PlacingAccessModifiersOnSetters.cs index 8a667e771..e08b82ac7 100644 --- a/src/Chapter06/Listing06.23.PlacingAccessModifiersOnSetters.cs +++ b/src/Chapter06/Listing06.23.PlacingAccessModifiersOnSetters.cs @@ -1,46 +1,45 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 // Pending a constructors -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_23; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee1 = new(); - employee1.Initialize(42); - #if COMPILEERROR // EXCLUDE - #region HIGHLIGHT - // ERROR: The property or indexer 'Employee.Id' - // cannot be used in this context because the set - // accessor is inaccessible - employee1.Id = "490"; - #endregion HIGHLIGHT - #endif // COMPILEERROR // EXCLUDE - } + Employee employee1 = new(); + employee1.Initialize(42); + #if COMPILEERROR // EXCLUDE + #region HIGHLIGHT + // ERROR: The property or indexer 'Employee.Id' + // cannot be used in this context because the set + // accessor is inaccessible + employee1.Id = "490"; + #endregion HIGHLIGHT + #endif // COMPILEERROR // EXCLUDE } +} - public class Employee +public class Employee +{ + public void Initialize(int id) { - public void Initialize(int id) - { - #region HIGHLIGHT - // Set Id property - Id = id.ToString(); - #endregion HIGHLIGHT - } + #region HIGHLIGHT + // Set Id property + Id = id.ToString(); + #endregion HIGHLIGHT + } - // ... - // Id property declaration - public string Id - { - get => _Id; - #region HIGHLIGHT - private set => _Id = value; - #endregion HIGHLIGHT - } - private string _Id; + // ... + // Id property declaration + public string Id + { + get => _Id; + #region HIGHLIGHT + private set => _Id = value; + #endregion HIGHLIGHT } - #endregion INCLUDE + private string _Id; } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.26.DefiningAConstructor.cs b/src/Chapter06/Listing06.26.DefiningAConstructor.cs index 6a68bc37d..693a37052 100644 --- a/src/Chapter06/Listing06.26.DefiningAConstructor.cs +++ b/src/Chapter06/Listing06.26.DefiningAConstructor.cs @@ -1,74 +1,73 @@ // Disabled pending introductin to object initializers #pragma warning disable IDE0017 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_26 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_26; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - Employee employee; - employee = new("Inigo", "Montoya"); - employee.Salary = "Too Little"; + Employee employee; + employee = new("Inigo", "Montoya"); + employee.Salary = "Too Little"; - System.Console.WriteLine( - "{0} {1}: {2}", - employee.FirstName, - employee.LastName, - employee.Salary); - } + System.Console.WriteLine( + "{0} {1}: {2}", + employee.FirstName, + employee.LastName, + employee.Salary); } +} - #region INCLUDE - public class Employee +#region INCLUDE +public class Employee +{ + #region HIGHLIGHT + // Employee constructor + public Employee(string firstName, string lastName) { - #region HIGHLIGHT - // Employee constructor - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } - #endregion HIGHLIGHT + FirstName = firstName; + LastName = lastName; + } + #endregion HIGHLIGHT - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; - #region EXCLUDE - public string? Title { get; set; } - public Employee? Manager { get; set; } + #region EXCLUDE + public string? Title { get; set; } + public Employee? Manager { get; set; } - // Name property - public string Name + // Name property + public string Name + { + get + { + return FirstName + " " + LastName; + } + set { - get + // Split the assigned value into + // first and last names + string[] names; + names = value.Split(new char[] { ' ' }); + if(names.Length == 2) { - return FirstName + " " + LastName; + FirstName = names[0]; + LastName = names[1]; } - set + else { - // Split the assigned value into - // first and last names - string[] names; - names = value.Split(new char[] { ' ' }); - if(names.Length == 2) - { - FirstName = names[0]; - LastName = names[1]; - } - else - { - // Throw an exception if the full - // name was not assigned - throw new System.ArgumentException( - string.Format( - $"Assigned value '{ value }' is invalid", - nameof(value))); - } + // Throw an exception if the full + // name was not assigned + throw new System.ArgumentException( + string.Format( + $"Assigned value '{ value }' is invalid", + nameof(value))); } } - #endregion EXCLUDE } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.27.CallingAConstructor.cs b/src/Chapter06/Listing06.27.CallingAConstructor.cs index 1c064d3f0..7ed879528 100644 --- a/src/Chapter06/Listing06.27.CallingAConstructor.cs +++ b/src/Chapter06/Listing06.27.CallingAConstructor.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_27 -{ - using Listing06_26; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_27; + +using Listing06_26; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee; - #region HIGHLIGHT - employee = new("Inigo", "Montoya"); - #endregion HIGHLIGHT - employee.Salary = "Too Little"; + Employee employee; + #region HIGHLIGHT + employee = new("Inigo", "Montoya"); + #endregion HIGHLIGHT + employee.Salary = "Too Little"; - System.Console.WriteLine( - "{0} {1}: {2}", - employee.FirstName, - employee.LastName, - employee.Salary); - } - // ... + System.Console.WriteLine( + "{0} {1}: {2}", + employee.FirstName, + employee.LastName, + employee.Salary); } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.28.DefaultConstructorNoLongerAvailable.cs b/src/Chapter06/Listing06.28.DefaultConstructorNoLongerAvailable.cs index b1023ec3a..41962bc91 100644 --- a/src/Chapter06/Listing06.28.DefaultConstructorNoLongerAvailable.cs +++ b/src/Chapter06/Listing06.28.DefaultConstructorNoLongerAvailable.cs @@ -1,27 +1,26 @@ // Variable is declared but never used #pragma warning disable CS0168 -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_28 -{ - using Listing06_26; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_28; + +using Listing06_26; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee; + Employee employee; - #if COMPILEERROR // EXCLUDE - #region HIGHLIGHT - // ERROR: No overload because method 'Employee' - // takes '0' arguments - employee = new Employee(); - #endregion HIGHLIGHT - #endif // COMPILEERROR // EXCLUDE + #if COMPILEERROR // EXCLUDE + #region HIGHLIGHT + // ERROR: No overload because method 'Employee' + // takes '0' arguments + employee = new Employee(); + #endregion HIGHLIGHT + #endif // COMPILEERROR // EXCLUDE - // ... - } + // ... } -#endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.29.CallingAnObjectInitializerWithExplicitMemberAssignment.cs b/src/Chapter06/Listing06.29.CallingAnObjectInitializerWithExplicitMemberAssignment.cs index 55f79013b..58d93de48 100644 --- a/src/Chapter06/Listing06.29.CallingAnObjectInitializerWithExplicitMemberAssignment.cs +++ b/src/Chapter06/Listing06.29.CallingAnObjectInitializerWithExplicitMemberAssignment.cs @@ -1,64 +1,63 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_29 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_29; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Employee employee = new("Inigo", "Montoya") - { Title = "Computer Nerd", Salary = "Not enough" }; - #region EXCLUDE - System.Console.WriteLine( - "{0} {1} ({2}): {3}", - employee.FirstName, - employee.LastName, - employee.Title, - employee.Salary); - #endregion EXCLUDE - } + Employee employee = new("Inigo", "Montoya") + { Title = "Computer Nerd", Salary = "Not enough" }; + #region EXCLUDE + System.Console.WriteLine( + "{0} {1} ({2}): {3}", + employee.FirstName, + employee.LastName, + employee.Title, + employee.Salary); + #endregion EXCLUDE } - #endregion INCLUDE +} +#endregion INCLUDE - public class Employee +public class Employee +{ + // Employee constructor + public Employee(string firstName, string lastName) { - // Employee constructor - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } + FirstName = firstName; + LastName = lastName; + } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; - public string? Title { get; set; } - public Employee? Manager { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; + public string? Title { get; set; } + public Employee? Manager { get; set; } - // Name property - public string Name + // Name property + public string Name + { + get + { + return FirstName + " " + LastName; + } + set { - get + // Split the assigned value into + // first and last names + string[] names; + names = value.Split(new char[] { ' ' }); + if(names.Length == 2) { - return FirstName + " " + LastName; + FirstName = names[0]; + LastName = names[1]; } - set + else { - // Split the assigned value into - // first and last names - string[] names; - names = value.Split(new char[] { ' ' }); - if(names.Length == 2) - { - FirstName = names[0]; - LastName = names[1]; - } - else - { - // Throw an exception if the full - // name was not assigned - throw new System.ArgumentException( - $"Assigned value '{value}' is invalid"); - } + // Throw an exception if the full + // name was not assigned + throw new System.ArgumentException( + $"Assigned value '{value}' is invalid"); } } } diff --git a/src/Chapter06/Listing06.30.CallingAnObjectInitializer.cs b/src/Chapter06/Listing06.30.CallingAnObjectInitializer.cs index d15e42dcc..9a2841ae6 100644 --- a/src/Chapter06/Listing06.30.CallingAnObjectInitializer.cs +++ b/src/Chapter06/Listing06.30.CallingAnObjectInitializer.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_30 -{ - using System.Collections.Generic; - using Listing06_26; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_30; + +using System.Collections.Generic; +using Listing06_26; - #region INCLUDE - public class Program +#region INCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - List employees = new() - { - new("Inigo", "Montoya"), - new("Kevin", "Bost") - }; - // ... - } + List employees = new() + { + new("Inigo", "Montoya"), + new("Kevin", "Bost") + }; + // ... } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.31.InitOnlySetters.cs b/src/Chapter06/Listing06.31.InitOnlySetters.cs index 3135745fe..f232e69a0 100644 --- a/src/Chapter06/Listing06.31.InitOnlySetters.cs +++ b/src/Chapter06/Listing06.31.InitOnlySetters.cs @@ -1,52 +1,51 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 // Pending a constructors -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_31 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_31; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + public Employee(int id, string name) { - public Employee(int id, string name) - { - Id = id; - Name = name; - Salary = null; - } + Id = id; + Name = name; + Salary = null; + } - // ... + // ... - public int Id { get; } - public string Name { get; } + public int Id { get; } + public string Name { get; } - public string? Salary - { - get => _Salary; - #region HIGHLIGHT - init => _Salary = value; - #endregion HIGHLIGHT - } - private string? _Salary; + public string? Salary + { + get => _Salary; + #region HIGHLIGHT + init => _Salary = value; + #endregion HIGHLIGHT } + private string? _Salary; +} - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region HIGHLIGHT - Employee employee = new(42, "Inigo Montoya") - { - Salary = "Sufficient" - }; - #endregion HIGHLIGHT + #region HIGHLIGHT + Employee employee = new(42, "Inigo Montoya") + { + Salary = "Sufficient" + }; + #endregion HIGHLIGHT - #if COMPILEERROR // EXCLUDE - #region HIGHLIGHT - // ERROR: Property or indexer 'Employee.Salary' - // cannot be assigned after initialization completes. - employee.Salary = "Enough"; - #endregion HIGHLIGHT - #endif // COMPILEERROR // EXCLUDE - } + #if COMPILEERROR // EXCLUDE + #region HIGHLIGHT + // ERROR: Property or indexer 'Employee.Salary' + // cannot be assigned after initialization completes. + employee.Salary = "Enough"; + #endregion HIGHLIGHT + #endif // COMPILEERROR // EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.32.OverloadingAConstructor.cs b/src/Chapter06/Listing06.32.OverloadingAConstructor.cs index 289c4f779..1546ae7ea 100644 --- a/src/Chapter06/Listing06.32.OverloadingAConstructor.cs +++ b/src/Chapter06/Listing06.32.OverloadingAConstructor.cs @@ -2,56 +2,55 @@ #pragma warning disable IDE0044 #pragma warning disable 649 // _Id is never assigned -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_32 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_32; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + public Employee(string firstName, string lastName) { - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } + FirstName = firstName; + LastName = lastName; + } - #region HIGHLIGHT - public Employee( - int id, string firstName, string lastName) - { - Id = id; - FirstName = firstName; - LastName = lastName; - } + #region HIGHLIGHT + public Employee( + int id, string firstName, string lastName) + { + Id = id; + FirstName = firstName; + LastName = lastName; + } - // FirstName & LastName set inside Id property setter. - #pragma warning disable CS8618 - public Employee(int id) => Id = id; - #pragma warning restore CS8618 + // FirstName & LastName set inside Id property setter. + #pragma warning disable CS8618 + public Employee(int id) => Id = id; + #pragma warning restore CS8618 - private int _Id; - public int Id + private int _Id; + public int Id + { + get => _Id; + private set { - get => _Id; - private set - { - // Look up employee name... - // ... - } + // Look up employee name... + // ... } - #endregion HIGHLIGHT - #region EXCLUDE - [System.Diagnostics.CodeAnalysis.NotNull] - [System.Diagnostics.CodeAnalysis.DisallowNull] - #endregion EXCLUDE - public string FirstName { get; set; } - #region EXCLUDE - [System.Diagnostics.CodeAnalysis.DisallowNull] - [System.Diagnostics.CodeAnalysis.NotNull] - #endregion EXCLUDE - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; + } + #endregion HIGHLIGHT + #region EXCLUDE + [System.Diagnostics.CodeAnalysis.NotNull] + [System.Diagnostics.CodeAnalysis.DisallowNull] + #endregion EXCLUDE + public string FirstName { get; set; } + #region EXCLUDE + [System.Diagnostics.CodeAnalysis.DisallowNull] + [System.Diagnostics.CodeAnalysis.NotNull] + #endregion EXCLUDE + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.33.CallingOneConstructorFromAnother.cs b/src/Chapter06/Listing06.33.CallingOneConstructorFromAnother.cs index 422f5c442..5bd312e45 100644 --- a/src/Chapter06/Listing06.33.CallingOneConstructorFromAnother.cs +++ b/src/Chapter06/Listing06.33.CallingOneConstructorFromAnother.cs @@ -1,46 +1,45 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_33 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_33; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + public Employee(string firstName, string lastName) { - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } + FirstName = firstName; + LastName = lastName; + } - #region HIGHLIGHT - public Employee( - int id, string firstName, string lastName) - : this(firstName, lastName) - #endregion HIGHLIGHT - { - Id = id; - } + #region HIGHLIGHT + public Employee( + int id, string firstName, string lastName) + : this(firstName, lastName) + #endregion HIGHLIGHT + { + Id = id; + } - // FirstName&LastName set inside Id property setter. - #pragma warning disable CS8618 - public Employee(int id) - { - Id = id; + // FirstName&LastName set inside Id property setter. + #pragma warning disable CS8618 + public Employee(int id) + { + Id = id; - // Look up employee name... - // ... + // Look up employee name... + // ... - #region HIGHLIGHT - // NOTE: Member constructors cannot be - // called explicitly inline - // this(id, firstName, lastName); - #endregion HIGHLIGHT - } - #pragma warning restore CS8618 + #region HIGHLIGHT + // NOTE: Member constructors cannot be + // called explicitly inline + // this(id, firstName, lastName); + #endregion HIGHLIGHT + } + #pragma warning restore CS8618 - public int Id { get; private set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; + public int Id { get; private set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.34.ProvidingAnInitializationMethod.cs b/src/Chapter06/Listing06.34.ProvidingAnInitializationMethod.cs index 0b0d2aa8d..475bbeca8 100644 --- a/src/Chapter06/Listing06.34.ProvidingAnInitializationMethod.cs +++ b/src/Chapter06/Listing06.34.ProvidingAnInitializationMethod.cs @@ -1,101 +1,100 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_34 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_34; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - System.Console.WriteLine("No output in this example"); - } + System.Console.WriteLine("No output in this example"); } +} - #region INCLUDE - public class Employee +#region INCLUDE +public class Employee +{ + // FirstName&LastName set inside Initialize() method. + #pragma warning disable CS8618 + public Employee(string firstName, string lastName) { - // FirstName&LastName set inside Initialize() method. - #pragma warning disable CS8618 - public Employee(string firstName, string lastName) - { - int id; - // Generate an employee ID... - #region EXCLUDE - id = 0; // id needs to be initialized for this example - #endregion EXCLUDE - #region HIGHLIGHT - Initialize(id, firstName, lastName); - #endregion HIGHLIGHT - } - - public Employee(int id, string firstName, string lastName) - { - #region HIGHLIGHT - Initialize(id, firstName, lastName); - #endregion HIGHLIGHT - } + int id; + // Generate an employee ID... + #region EXCLUDE + id = 0; // id needs to be initialized for this example + #endregion EXCLUDE + #region HIGHLIGHT + Initialize(id, firstName, lastName); + #endregion HIGHLIGHT + } - public Employee(int id) - { - string firstName; - string lastName; - Id = id; + public Employee(int id, string firstName, string lastName) + { + #region HIGHLIGHT + Initialize(id, firstName, lastName); + #endregion HIGHLIGHT + } - // Look up employee data - #region EXCLUDE - firstName = string.Empty; - lastName = string.Empty; - #endregion EXCLUDE + public Employee(int id) + { + string firstName; + string lastName; + Id = id; - #region HIGHLIGHT - Initialize(id, firstName, lastName); - #endregion HIGHLIGHT - } - #pragma warning restore CS8618 + // Look up employee data + #region EXCLUDE + firstName = string.Empty; + lastName = string.Empty; + #endregion EXCLUDE #region HIGHLIGHT - private void Initialize( - int id, string firstName, string lastName) - { - Id = id; - FirstName = firstName; - LastName = lastName; - } + Initialize(id, firstName, lastName); #endregion HIGHLIGHT - #region EXCLUDE + } + #pragma warning restore CS8618 + + #region HIGHLIGHT + private void Initialize( + int id, string firstName, string lastName) + { + Id = id; + FirstName = firstName; + LastName = lastName; + } + #endregion HIGHLIGHT + #region EXCLUDE - public int Id { get; private set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; - public string? Title { get; set; } - public Employee? Manager { get; set; } + public int Id { get; private set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; + public string? Title { get; set; } + public Employee? Manager { get; set; } - // Name property - public string Name + // Name property + public string Name + { + get + { + return FirstName + " " + LastName; + } + set { - get + // Split the assigned value into + // first and last names + string[] names; + names = value.Split(new char[] { ' ' }); + if(names.Length == 2) { - return FirstName + " " + LastName; + FirstName = names[0]; + LastName = names[1]; } - set + else { - // Split the assigned value into - // first and last names - string[] names; - names = value.Split(new char[] { ' ' }); - if(names.Length == 2) - { - FirstName = names[0]; - LastName = names[1]; - } - else - { - // Throw an exception if the full - // name was not assigned - throw new System.ArgumentException( - $"Assigned value '{value}' is invalid"); - } + // Throw an exception if the full + // name was not assigned + throw new System.ArgumentException( + $"Assigned value '{value}' is invalid"); } } - #endregion EXCLUDE } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.35.ProvidingValidationOnNon-NullableProperty.cs b/src/Chapter06/Listing06.35.ProvidingValidationOnNon-NullableProperty.cs index 0cdd72787..fbaea9ba8 100644 --- a/src/Chapter06/Listing06.35.ProvidingValidationOnNon-NullableProperty.cs +++ b/src/Chapter06/Listing06.35.ProvidingValidationOnNon-NullableProperty.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_35 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_35; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Employee employee = new("Inigo Montoya"); + Employee employee = new("Inigo Montoya"); - System.Console.WriteLine(employee.Name); + System.Console.WriteLine(employee.Name); - // ... - } + // ... } - #region INCLUDE - public class Employee +} +#region INCLUDE +public class Employee +{ + public Employee(string name) { - public Employee(string name) - { - #region HIGHLIGHT - Name = name; - #endregion HIGHLIGHT - } + #region HIGHLIGHT + Name = name; + #endregion HIGHLIGHT + } - public string Name - { - #region HIGHLIGHT - get => _Name!; - set => _Name = value ?? throw new ArgumentNullException( - nameof(value)); - #endregion HIGHLIGHT - } - private string? _Name; - // ... + public string Name + { + #region HIGHLIGHT + get => _Name!; + set => _Name = value ?? throw new ArgumentNullException( + nameof(value)); + #endregion HIGHLIGHT } - #endregion INCLUDE + private string? _Name; + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.36.ValidationOfNonNullReferenceTypeAutomaticallyImplementedProperties.cs b/src/Chapter06/Listing06.36.ValidationOfNonNullReferenceTypeAutomaticallyImplementedProperties.cs index b5e62904b..96c38a6d0 100644 --- a/src/Chapter06/Listing06.36.ValidationOfNonNullReferenceTypeAutomaticallyImplementedProperties.cs +++ b/src/Chapter06/Listing06.36.ValidationOfNonNullReferenceTypeAutomaticallyImplementedProperties.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_36 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_36; - #region INCLUDE - public class Employee - { - public Employee(string name) - { - #region HIGHLIGHT - Name = name ?? throw new ArgumentNullException(nameof(name)); - #endregion HIGHLIGHT - } +using System; +#region INCLUDE +public class Employee +{ + public Employee(string name) + { #region HIGHLIGHT - public string Name { get; } + Name = name ?? throw new ArgumentNullException(nameof(name)); #endregion HIGHLIGHT } - #endregion INCLUDE + + #region HIGHLIGHT + public string Name { get; } + #endregion HIGHLIGHT } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.37.RequiredProperties.cs b/src/Chapter06/Listing06.37.RequiredProperties.cs index 47ad0b1e0..e09e7e336 100644 --- a/src/Chapter06/Listing06.37.RequiredProperties.cs +++ b/src/Chapter06/Listing06.37.RequiredProperties.cs @@ -1,62 +1,61 @@ #if NET7_0_OR_GREATER -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_37 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_37; + +#region INCLUDE +public class Book { - #region INCLUDE - public class Book + string? _Title; + #region HIGHLIGHT + public required string Title + #endregion HIGHLIGHT { - string? _Title; - #region HIGHLIGHT - public required string Title - #endregion HIGHLIGHT + get + { + return _Title!; + } + set { - get - { - return _Title!; - } - set - { - _Title = value ?? throw new ArgumentNullException(nameof(value)); - } + _Title = value ?? throw new ArgumentNullException(nameof(value)); } + } - string? _Isbn; - #region HIGHLIGHT - public required string Isbn - #endregion HIGHLIGHT + string? _Isbn; + #region HIGHLIGHT + public required string Isbn + #endregion HIGHLIGHT + { + get + { + return _Isbn!; + } + set { - get - { - return _Isbn!; - } - set - { - _Isbn = value ?? throw new ArgumentNullException(nameof(value)); - } + _Isbn = value ?? throw new ArgumentNullException(nameof(value)); } + } - public string? Subtitle { get; set; } + public string? Subtitle { get; set; } - // ... - } + // ... +} - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region EXCLUDE + #pragma warning disable IDE0059 // Unnecessary assignment of a value + #endregion EXCLUDE + Book book = new() { - #region EXCLUDE - #pragma warning disable IDE0059 // Unnecessary assignment of a value - #endregion EXCLUDE - Book book = new() - { - Isbn = "978-0135972267", - Title = "Harold and the Purple Crayon" - }; - #region EXCLUDE - #pragma warning restore IDE0059 // Unnecessary assignment of a value - #endregion EXCLUDE - } + Isbn = "978-0135972267", + Title = "Harold and the Purple Crayon" + }; + #region EXCLUDE + #pragma warning restore IDE0059 // Unnecessary assignment of a value + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE #endif // NET7_0_OR_GREATER diff --git a/src/Chapter06/Listing06.38.SpecifyingRequiredMembersWithinTheObjectInitializer.cs b/src/Chapter06/Listing06.38.SpecifyingRequiredMembersWithinTheObjectInitializer.cs index 3ac34186b..4e40eca6c 100644 --- a/src/Chapter06/Listing06.38.SpecifyingRequiredMembersWithinTheObjectInitializer.cs +++ b/src/Chapter06/Listing06.38.SpecifyingRequiredMembersWithinTheObjectInitializer.cs @@ -6,23 +6,22 @@ using System.Runtime.CompilerServices; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_38 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_38; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #if COMPILEERROR // EXCLUDE - #region INCLUDE - // Error CS9035: - // Required member 'Book.Isbn' must be set in the object - // initializer or attribute constructor - Book book = new() { Title= "Essential C#" }; + #if COMPILEERROR // EXCLUDE + #region INCLUDE + // Error CS9035: + // Required member 'Book.Isbn' must be set in the object + // initializer or attribute constructor + Book book = new() { Title= "Essential C#" }; - // ... - #endregion INCLUDE - #endif // COMPILEERROR // EXCLUDE - } - } + // ... + #endregion INCLUDE + #endif // COMPILEERROR // EXCLUDE + } } #endif // NET7_0_OR_GREATER diff --git a/src/Chapter06/Listing06.39.DisablingRequiredObjectInitialization.cs b/src/Chapter06/Listing06.39.DisablingRequiredObjectInitialization.cs index 86ebe334f..883411e6e 100644 --- a/src/Chapter06/Listing06.39.DisablingRequiredObjectInitialization.cs +++ b/src/Chapter06/Listing06.39.DisablingRequiredObjectInitialization.cs @@ -1,69 +1,68 @@ #if NET7_0_OR_GREATER using System.Diagnostics.CodeAnalysis; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_39 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_39; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - Book book = new(42) { - Subtitle = "The Comprehensive, Expert Guide " + - "to C# for Programmers at all levels" }; - } + Book book = new(42) { + Subtitle = "The Comprehensive, Expert Guide " + + "to C# for Programmers at all levels" }; } +} - public class Book +public class Book +{ + #region INCLUDE + [SetsRequiredMembers] + public Book(int id) { - #region INCLUDE - [SetsRequiredMembers] - public Book(int id) - { - Id = id; + Id = id; - // Look up book data - #region EXCLUDE - Title = string.Empty; - Isbn = string.Empty; - #endregion EXCLUDE - // ... - } - #endregion INCLUDE + // Look up book data + #region EXCLUDE + Title = string.Empty; + Isbn = string.Empty; + #endregion EXCLUDE + // ... + } + #endregion INCLUDE - public int Id { get; init; } + public int Id { get; init; } - string? _Title; - public required string Title + string? _Title; + public required string Title + { + get { - get - { - return _Title!; - } - set - { - ArgumentException.ThrowIfNullOrEmpty( - value = value?.Trim()!); - _Title = value; - } + return _Title!; } - - string? _Isbn; - public required string Isbn + set { - get - { - return _Isbn!; - } - set - { - ArgumentException.ThrowIfNullOrEmpty( - value = value?.Trim()!); - _Isbn = value; - } + ArgumentException.ThrowIfNullOrEmpty( + value = value?.Trim()!); + _Title = value; } - public string? Subtitle { get; set; } + } - // ... + string? _Isbn; + public required string Isbn + { + get + { + return _Isbn!; + } + set + { + ArgumentException.ThrowIfNullOrEmpty( + value = value?.Trim()!); + _Isbn = value; + } } + public string? Subtitle { get; set; } + + // ... } #endif // NET7_0_OR_GREATER diff --git a/src/Chapter06/Listing06.40.UsingNotNullWhenAndNotNullIfNotNullAttributes.cs b/src/Chapter06/Listing06.40.UsingNotNullWhenAndNotNullIfNotNullAttributes.cs index f80f08943..11083b298 100644 --- a/src/Chapter06/Listing06.40.UsingNotNullWhenAndNotNullIfNotNullAttributes.cs +++ b/src/Chapter06/Listing06.40.UsingNotNullWhenAndNotNullIfNotNullAttributes.cs @@ -1,40 +1,39 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_40 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_40; + +#region INCLUDE +using System.Diagnostics.CodeAnalysis; +#region EXCLUDE +public class NullabilityAttributesExamined { - #region INCLUDE - using System.Diagnostics.CodeAnalysis; - #region EXCLUDE - public class NullabilityAttributesExamined +#endregion EXCLUDE + static public bool TryGetDigitAsText( + char number, [NotNullWhen(true)]out string? text) => + (text = number switch + { + '1' => "one", + '2' => "two", + '3' => "three", + '4' => "four", + // ... + '9' => "nine", + _ => null + }) is not null; + + [return: NotNullIfNotNull("text")] + static public string? TryGetDigitsAsText(string? text) { - #endregion EXCLUDE - static public bool TryGetDigitAsText( - char number, [NotNullWhen(true)]out string? text) => - (text = number switch - { - '1' => "one", - '2' => "two", - '3' => "three", - '4' => "four", - // ... - '9' => "nine", - _ => null - }) is not null; + if (text == null) return null; - [return: NotNullIfNotNull("text")] - static public string? TryGetDigitsAsText(string? text) + string result = ""; + foreach (char character in text) { - if (text == null) return null; - - string result = ""; - foreach (char character in text) + if (TryGetDigitAsText(character, out string? digitText)) { - if (TryGetDigitAsText(character, out string? digitText)) - { - if (result != "") result += '-'; - result += digitText.ToLower(); - } + if (result != "") result += '-'; + result += digitText.ToLower(); } - return result; } - #endregion INCLUDE + return result; } +#endregion INCLUDE } diff --git a/src/Chapter06/Listing06.41.PotentialNullReturnWithMaybeNullAttribute.cs b/src/Chapter06/Listing06.41.PotentialNullReturnWithMaybeNullAttribute.cs index 3d1a62dfb..e9d4d3899 100644 --- a/src/Chapter06/Listing06.41.PotentialNullReturnWithMaybeNullAttribute.cs +++ b/src/Chapter06/Listing06.41.PotentialNullReturnWithMaybeNullAttribute.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_41 -{ - using System; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_41; + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Collections.Generic; - public class NullabilityAttributesExamined - { - static public string? Method() => - GetObject(Array.Empty(), (item) => true); - #region INCLUDE - // ... - [return: MaybeNull] - static public T GetObject( - IEnumerable sequence, Func match) - => - // ... - #endregion INCLUDE - sequence.FirstOrDefault(match); - } +public class NullabilityAttributesExamined +{ + static public string? Method() => + GetObject(Array.Empty(), (item) => true); + #region INCLUDE + // ... + [return: MaybeNull] + static public T GetObject( + IEnumerable sequence, Func match) + => + // ... + #endregion INCLUDE + sequence.FirstOrDefault(match); } diff --git a/src/Chapter06/Listing06.42.DefiningAndUsingADeconstructors.cs b/src/Chapter06/Listing06.42.DefiningAndUsingADeconstructors.cs index 044e34a60..41f7efcdb 100644 --- a/src/Chapter06/Listing06.42.DefiningAndUsingADeconstructors.cs +++ b/src/Chapter06/Listing06.42.DefiningAndUsingADeconstructors.cs @@ -1,120 +1,119 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_42 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_42; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + #region EXCLUDE + // FirstName&LastName set inside Initialize() method. + #pragma warning disable CS8618 + public Employee(string firstName, string lastName) { - #region EXCLUDE - // FirstName&LastName set inside Initialize() method. - #pragma warning disable CS8618 - public Employee(string firstName, string lastName) - { - int id; - // Generate an employee ID... - id = 0; // id needs to be initialized for this example - // ... - Initialize(id, firstName, lastName); - } + int id; + // Generate an employee ID... + id = 0; // id needs to be initialized for this example + // ... + Initialize(id, firstName, lastName); + } - public Employee(int id, string firstName, string lastName) - { - Initialize(id, firstName, lastName); - } + public Employee(int id, string firstName, string lastName) + { + Initialize(id, firstName, lastName); + } - public Employee(int id) - { - string firstName; - string lastName; - Id = id; + public Employee(int id) + { + string firstName; + string lastName; + Id = id; - // Look up employee data - firstName = string.Empty; - lastName = string.Empty; - // ... + // Look up employee data + firstName = string.Empty; + lastName = string.Empty; + // ... - Initialize(id, firstName, lastName); - } - #pragma warning disable CS8618 + Initialize(id, firstName, lastName); + } + #pragma warning disable CS8618 - private void Initialize( - int id, string firstName, string lastName) - { - Id = id; - FirstName = firstName; - LastName = lastName; - } - #endregion EXCLUDE - public void Deconstruct( - out int id, out string firstName, - out string lastName, out string? salary) + private void Initialize( + int id, string firstName, string lastName) + { + Id = id; + FirstName = firstName; + LastName = lastName; + } + #endregion EXCLUDE + public void Deconstruct( + out int id, out string firstName, + out string lastName, out string? salary) + { + (id, firstName, lastName, salary) = + (Id, FirstName, LastName, Salary); + } + #region EXCLUDE + public int Id { get; private set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; + public string? Title { get; set; } + public Employee? Manager { get; set; } + + // Name property + public string Name + { + get { - (id, firstName, lastName, salary) = - (Id, FirstName, LastName, Salary); + return FirstName + " " + LastName; } - #region EXCLUDE - public int Id { get; private set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; - public string? Title { get; set; } - public Employee? Manager { get; set; } - - // Name property - public string Name + set { - get + // Split the assigned value into + // first and last names. + string[] names; + names = value.Split(new char[] { ' ' }); + if(names.Length == 2) { - return FirstName + " " + LastName; + FirstName = names[0]; + LastName = names[1]; } - set + else { - // Split the assigned value into - // first and last names. - string[] names; - names = value.Split(new char[] { ' ' }); - if(names.Length == 2) - { - FirstName = names[0]; - LastName = names[1]; - } - else - { - // Throw an exception if the full - // name was not assigned. - throw new System.ArgumentException( - $"Assigned value '{value}' is invalid"); - } + // Throw an exception if the full + // name was not assigned. + throw new System.ArgumentException( + $"Assigned value '{value}' is invalid"); } } - #endregion EXCLUDE } + #endregion EXCLUDE +} - public class Program +public class Program +{ + public static void Main() { - public static void Main() + Employee employee; + employee = new ("Inigo", "Montoya") { - Employee employee; - employee = new ("Inigo", "Montoya") - { - // Leveraging object initializer syntax - Salary = "Too Little" - }; - #region EXCLUDE - System.Console.WriteLine( - "{0} {1}: {2}", - employee.FirstName, - employee.LastName, - employee.Salary); - #endregion EXCLUDE + // Leveraging object initializer syntax + Salary = "Too Little" + }; + #region EXCLUDE + System.Console.WriteLine( + "{0} {1}: {2}", + employee.FirstName, + employee.LastName, + employee.Salary); + #endregion EXCLUDE - #region HIGHLIGHT - employee.Deconstruct(out _, out string firstName, - out string lastName, out string? salary); - #endregion HIGHLIGHT + #region HIGHLIGHT + employee.Deconstruct(out _, out string firstName, + out string lastName, out string? salary); + #endregion HIGHLIGHT - System.Console.WriteLine( - "{0} {1}: {2}", - firstName, lastName, salary); - } + System.Console.WriteLine( + "{0} {1}: {2}", + firstName, lastName, salary); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.43.ImplicitlyInvokingDeconstructors.cs b/src/Chapter06/Listing06.43.ImplicitlyInvokingDeconstructors.cs index a2268fd88..d6b6f5470 100644 --- a/src/Chapter06/Listing06.43.ImplicitlyInvokingDeconstructors.cs +++ b/src/Chapter06/Listing06.43.ImplicitlyInvokingDeconstructors.cs @@ -1,35 +1,34 @@ using AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_42; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_43 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_43; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() + Employee employee; + employee = new ("Inigo", "Montoya") { - Employee employee; - employee = new ("Inigo", "Montoya") - { - // Leveraging object initializer syntax - Salary = "Too Little" - }; + // Leveraging object initializer syntax + Salary = "Too Little" + }; - #region EXCLUDE - System.Console.WriteLine( - "{0} {1}: {2}", - employee.FirstName, - employee.LastName, - employee.Salary); - #endregion EXCLUDE + #region EXCLUDE + System.Console.WriteLine( + "{0} {1}: {2}", + employee.FirstName, + employee.LastName, + employee.Salary); + #endregion EXCLUDE - #region HIGHLIGHT - (_, string firstName, string lastName, string? salary) = employee; - #endregion HIGHLIGHT + #region HIGHLIGHT + (_, string firstName, string lastName, string? salary) = employee; + #endregion HIGHLIGHT - System.Console.WriteLine( - "{0} {1}: {2}", - firstName, lastName, salary); - } + System.Console.WriteLine( + "{0} {1}: {2}", + firstName, lastName, salary); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.44.DeclaringAStaticField.cs b/src/Chapter06/Listing06.44.DeclaringAStaticField.cs index 93ac6d1e4..b42cb7a16 100644 --- a/src/Chapter06/Listing06.44.DeclaringAStaticField.cs +++ b/src/Chapter06/Listing06.44.DeclaringAStaticField.cs @@ -1,29 +1,28 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_44 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_44; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + public Employee(string firstName, string lastName) { - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - #region HIGHLIGHT - Id = NextId; - NextId++; - #endregion HIGHLIGHT - } - - // ... - + FirstName = firstName; + LastName = lastName; #region HIGHLIGHT - public static int NextId; + Id = NextId; + NextId++; #endregion HIGHLIGHT - public int Id { get; private set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; - - // ... } - #endregion INCLUDE + + // ... + + #region HIGHLIGHT + public static int NextId; + #endregion HIGHLIGHT + public int Id { get; private set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; + + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.45.AssigningAStaticFieldAtDeclaration.cs b/src/Chapter06/Listing06.45.AssigningAStaticFieldAtDeclaration.cs index 91a206e12..c1d2a9fec 100644 --- a/src/Chapter06/Listing06.45.AssigningAStaticFieldAtDeclaration.cs +++ b/src/Chapter06/Listing06.45.AssigningAStaticFieldAtDeclaration.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_45 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_45; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee - { - // ... - #region HIGHLIGHT - public static int NextId = 42; - #endregion HIGHLIGHT - // ... - } - #endregion INCLUDE + // ... + #region HIGHLIGHT + public static int NextId = 42; + #endregion HIGHLIGHT + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.46.AccessingAStaticField.cs b/src/Chapter06/Listing06.46.AccessingAStaticField.cs index 734197cdf..77cf1380a 100644 --- a/src/Chapter06/Listing06.46.AccessingAStaticField.cs +++ b/src/Chapter06/Listing06.46.AccessingAStaticField.cs @@ -1,58 +1,57 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_46 -{ - #region INCLUDE - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_46; + +#region INCLUDE +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region HIGHLIGHT - Employee.NextId = 1000000; - #endregion HIGHLIGHT + #region HIGHLIGHT + Employee.NextId = 1000000; + #endregion HIGHLIGHT - Employee employee1 = new( - "Inigo", "Montoya"); - Employee employee2 = new( - "Princess", "Buttercup"); + Employee employee1 = new( + "Inigo", "Montoya"); + Employee employee2 = new( + "Princess", "Buttercup"); - Console.WriteLine( - "{0} {1} ({2})", - employee1.FirstName, - employee1.LastName, - employee1.Id); - Console.WriteLine( - "{0} {1} ({2})", - employee2.FirstName, - employee2.LastName, - employee2.Id); + Console.WriteLine( + "{0} {1} ({2})", + employee1.FirstName, + employee1.LastName, + employee1.Id); + Console.WriteLine( + "{0} {1} ({2})", + employee2.FirstName, + employee2.LastName, + employee2.Id); - #region HIGHLIGHT - Console.WriteLine( - $"NextId = {Employee.NextId}"); - #endregion HIGHLIGHT - } - // ... + #region HIGHLIGHT + Console.WriteLine( + $"NextId = {Employee.NextId}"); + #endregion HIGHLIGHT } - #endregion INCLUDE - public class Employee + // ... +} +#endregion INCLUDE +public class Employee +{ + public Employee(string firstName, string lastName) { - public Employee(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - Id = NextId; - NextId++; - } + FirstName = firstName; + LastName = lastName; + Id = NextId; + NextId++; + } - // Field wrapped into property later in chapter - #pragma warning disable CA2211 //Non-constant fields should not be visible - public static int NextId = 42; - #pragma warning disable CA2211 + // Field wrapped into property later in chapter + #pragma warning disable CA2211 //Non-constant fields should not be visible + public static int NextId = 42; + #pragma warning disable CA2211 - public int Id { get; private set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string? Salary { get; set; } = "Not Enough"; - } + public int Id { get; private set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string? Salary { get; set; } = "Not Enough"; } diff --git a/src/Chapter06/Listing06.47.DefiningAStaticMethodOnDirectoryInfo.cs b/src/Chapter06/Listing06.47.DefiningAStaticMethodOnDirectoryInfo.cs index bf24172a8..51240ce91 100644 --- a/src/Chapter06/Listing06.47.DefiningAStaticMethodOnDirectoryInfo.cs +++ b/src/Chapter06/Listing06.47.DefiningAStaticMethodOnDirectoryInfo.cs @@ -1,71 +1,70 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_47 -{ - using System; - using System.IO; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_47; + +using System; +using System.IO; - #region INCLUDE - public static class DirectoryInfoExtension +#region INCLUDE +public static class DirectoryInfoExtension +{ + #region HIGHLIGHT + public static void CopyTo( + DirectoryInfo sourceDirectory, string target, + SearchOption option, string searchPattern) + #endregion HIGHLIGHT { - #region HIGHLIGHT - public static void CopyTo( - DirectoryInfo sourceDirectory, string target, - SearchOption option, string searchPattern) - #endregion HIGHLIGHT + if (target[^1] != + Path.DirectorySeparatorChar) { - if (target[^1] != - Path.DirectorySeparatorChar) - { - target += Path.DirectorySeparatorChar; - } - Directory.CreateDirectory(target); + target += Path.DirectorySeparatorChar; + } + Directory.CreateDirectory(target); - for (int i = 0; i < searchPattern.Length; i++) + for (int i = 0; i < searchPattern.Length; i++) + { + foreach (string file in + Directory.EnumerateFiles( + sourceDirectory.FullName, searchPattern)) { - foreach (string file in - Directory.EnumerateFiles( - sourceDirectory.FullName, searchPattern)) - { - File.Copy(file, - target + Path.GetFileName(file), true); - } + File.Copy(file, + target + Path.GetFileName(file), true); } + } - // Copy subdirectories (recursively) - if (option == SearchOption.AllDirectories) + // Copy subdirectories (recursively) + if (option == SearchOption.AllDirectories) + { + foreach (string element in + Directory.EnumerateDirectories( + sourceDirectory.FullName)) { - foreach (string element in - Directory.EnumerateDirectories( - sourceDirectory.FullName)) - { - Copy(element, - target + Path.GetFileName(element), - searchPattern); - } + Copy(element, + target + Path.GetFileName(element), + searchPattern); } } - #region EXCLUDE - private static void Copy(string element, string fileName, string searchPattern) - { - Console.WriteLine( - $"Copying(element: {element}, fileName: {fileName}, searchPattern: {searchPattern})"); - } - #endregion EXCLUDE } + #region EXCLUDE + private static void Copy(string element, string fileName, string searchPattern) + { + Console.WriteLine( + $"Copying(element: {element}, fileName: {fileName}, searchPattern: {searchPattern})"); + } + #endregion EXCLUDE +} - public class Program +public class Program +{ + public static void Main(params string[] args) { - public static void Main(params string[] args) - { - DirectoryInfo source = new(args[0]); - string target = args[1]; + DirectoryInfo source = new(args[0]); + string target = args[1]; - #region HIGHLIGHT - DirectoryInfoExtension.CopyTo( - source, target, - SearchOption.AllDirectories, "*"); - #endregion HIGHLIGHT - } + #region HIGHLIGHT + DirectoryInfoExtension.CopyTo( + source, target, + SearchOption.AllDirectories, "*"); + #endregion HIGHLIGHT } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.48.DeclaringAStaticConstructor.cs b/src/Chapter06/Listing06.48.DeclaringAStaticConstructor.cs index c55da8623..53b6ed29c 100644 --- a/src/Chapter06/Listing06.48.DeclaringAStaticConstructor.cs +++ b/src/Chapter06/Listing06.48.DeclaringAStaticConstructor.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_48 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_48; - #region INCLUDE - public class Employee - { - static Employee() - { - Random randomGenerator = new(); - NextId = randomGenerator.Next(101, 999); - } +using System; - // ... - public static int NextId = 42; - // ... +#region INCLUDE +public class Employee +{ + static Employee() + { + Random randomGenerator = new(); + NextId = randomGenerator.Next(101, 999); } - #endregion INCLUDE + + // ... + public static int NextId = 42; + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.49.DeclaringAStaticProperty.cs b/src/Chapter06/Listing06.49.DeclaringAStaticProperty.cs index 975ccfed8..f88178c7d 100644 --- a/src/Chapter06/Listing06.49.DeclaringAStaticProperty.cs +++ b/src/Chapter06/Listing06.49.DeclaringAStaticProperty.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_49 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_49; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + // ... + #region HIGHLIGHT + public static int NextId { - // ... - #region HIGHLIGHT - public static int NextId + get { - get - { - return _NextId; - } - private set - { - _NextId = value; - } + return _NextId; + } + private set + { + _NextId = value; } - public static int _NextId = 42; - #endregion HIGHLIGHT - // ... } - #endregion INCLUDE + public static int _NextId = 42; + #endregion HIGHLIGHT + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.50.DeclaringAStaticClass.cs b/src/Chapter06/Listing06.50.DeclaringAStaticClass.cs index 06ba0ca6d..e07eb8b40 100644 --- a/src/Chapter06/Listing06.50.DeclaringAStaticClass.cs +++ b/src/Chapter06/Listing06.50.DeclaringAStaticClass.cs @@ -1,76 +1,75 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_50 -{ - using System; - using static SimpleMath; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_50; + +using System; +using static SimpleMath; - #region INCLUDE - #region HIGHLIGHT - public static class SimpleMath - #endregion HIGHLIGHT +#region INCLUDE +#region HIGHLIGHT +public static class SimpleMath +#endregion HIGHLIGHT +{ + // params allows the number of parameters to vary + public static int Max(params int[] numbers) { - // params allows the number of parameters to vary - public static int Max(params int[] numbers) + // Check that there is at least one item in numbers + if(numbers.Length == 0) { - // Check that there is at least one item in numbers - if(numbers.Length == 0) - { - throw new ArgumentException( - "numbers cannot be empty", nameof(numbers)); - } + throw new ArgumentException( + "numbers cannot be empty", nameof(numbers)); + } - int result; - result = numbers[0]; - foreach(int number in numbers) + int result; + result = numbers[0]; + foreach(int number in numbers) + { + if(number > result) { - if(number > result) - { - result = number; - } + result = number; } - return result; } + return result; + } - // params allows the number of parameters to vary - public static int Min(params int[] numbers) + // params allows the number of parameters to vary + public static int Min(params int[] numbers) + { + // Check that there is at least one item in numbers + if(numbers.Length == 0) { - // Check that there is at least one item in numbers - if(numbers.Length == 0) - { - throw new ArgumentException( - "numbers cannot be empty", nameof(numbers)); - } + throw new ArgumentException( + "numbers cannot be empty", nameof(numbers)); + } - int result; - result = numbers[0]; - foreach(int number in numbers) + int result; + result = numbers[0]; + foreach(int number in numbers) + { + if(number < result) { - if(number < result) - { - result = number; - } + result = number; } - return result; } + return result; } +} - public class Program +public class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) + int[] numbers = new int[args.Length]; + for (int count = 0; count < args.Length; count++) { - int[] numbers = new int[args.Length]; - for (int count = 0; count < args.Length; count++) - { - numbers[count] = args[count].Length; - } + numbers[count] = args[count].Length; + } - Console.WriteLine( - $@"Longest argument length = { - Max(numbers) }"); + Console.WriteLine( + $@"Longest argument length = { + Max(numbers) }"); - Console.WriteLine( - $@"Shortest argument length = { - Min(numbers) }"); - } + Console.WriteLine( + $@"Shortest argument length = { + Min(numbers) }"); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.51.StaticCopyMethodForDirectoryInfo.cs b/src/Chapter06/Listing06.51.StaticCopyMethodForDirectoryInfo.cs index dae2aa875..c7f996a3f 100644 --- a/src/Chapter06/Listing06.51.StaticCopyMethodForDirectoryInfo.cs +++ b/src/Chapter06/Listing06.51.StaticCopyMethodForDirectoryInfo.cs @@ -1,74 +1,73 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_51 -{ - using System; - using System.IO; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_51; + +using System; +using System.IO; - #region INCLUDE - public static class DirectoryInfoExtension +#region INCLUDE +public static class DirectoryInfoExtension +{ + public static void CopyTo( + #region HIGHLIGHT + this DirectoryInfo sourceDirectory, string target, + #endregion HIGHLIGHT + SearchOption option, string searchPattern) { - public static void CopyTo( - #region HIGHLIGHT - this DirectoryInfo sourceDirectory, string target, - #endregion HIGHLIGHT - SearchOption option, string searchPattern) + #region EXCLUDE + if (target[target.Length - 1] != Path.DirectorySeparatorChar) { - #region EXCLUDE - if (target[target.Length - 1] != Path.DirectorySeparatorChar) - { - target += Path.DirectorySeparatorChar; - } - if(!Directory.Exists(target)) - { - Directory.CreateDirectory(target); - } + target += Path.DirectorySeparatorChar; + } + if(!Directory.Exists(target)) + { + Directory.CreateDirectory(target); + } - for(int i = 0; i < searchPattern.Length; i++) + for(int i = 0; i < searchPattern.Length; i++) + { + foreach(string file in + Directory.GetFiles( + sourceDirectory.FullName, searchPattern)) { - foreach(string file in - Directory.GetFiles( - sourceDirectory.FullName, searchPattern)) - { - File.Copy(file, - target + Path.GetFileName(file), true); - } + File.Copy(file, + target + Path.GetFileName(file), true); } + } - //Copy SubDirectories (recursively) - if(option == SearchOption.AllDirectories) + //Copy SubDirectories (recursively) + if(option == SearchOption.AllDirectories) + { + foreach(string element in + Directory.GetDirectories( + sourceDirectory.FullName)) { - foreach(string element in - Directory.GetDirectories( - sourceDirectory.FullName)) - { - Copy(element, - target + Path.GetFileName(element), - searchPattern); - } + Copy(element, + target + Path.GetFileName(element), + searchPattern); } } + } - private static void Copy(string element, string fileName, string searchPattern) - { - Console.WriteLine("Copying " + fileName); - #endregion EXCLUDE - } + private static void Copy(string element, string fileName, string searchPattern) + { + Console.WriteLine("Copying " + fileName); + #endregion EXCLUDE } +} - #region EXCLUDE - public class Program +#region EXCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - DirectoryInfo directory = new(".\\Source"); - #region HIGHLIGHT - directory.CopyTo(".\\Target", - SearchOption.TopDirectoryOnly, "*"); - #endregion HIGHLIGHT - #region EXCLUDE - //Extension method. Is Defined above but appears to be a member of the DirectoryInfo object, directory, defined aboves - #endregion EXCLUDE - } + #endregion EXCLUDE + DirectoryInfo directory = new(".\\Source"); + #region HIGHLIGHT + directory.CopyTo(".\\Target", + SearchOption.TopDirectoryOnly, "*"); + #endregion HIGHLIGHT + #region EXCLUDE + //Extension method. Is Defined above but appears to be a member of the DirectoryInfo object, directory, defined aboves + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.52.DeclaringAConstantField.cs b/src/Chapter06/Listing06.52.DeclaringAConstantField.cs index 4cf9ef738..9049f86a5 100644 --- a/src/Chapter06/Listing06.52.DeclaringAConstantField.cs +++ b/src/Chapter06/Listing06.52.DeclaringAConstantField.cs @@ -1,11 +1,10 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_52 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_52; + +#region INCLUDE +public class ConvertUnits { - #region INCLUDE - public class ConvertUnits - { - public const float CentimetersPerInch = 2.54F; - public const int CupsPerGallon = 16; - // ... - } - #endregion INCLUDE + public const float CentimetersPerInch = 2.54F; + public const int CupsPerGallon = 16; + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.53.DeclaringAFieldAsReadonly.cs b/src/Chapter06/Listing06.53.DeclaringAFieldAsReadonly.cs index 24c88109e..19ca85741 100644 --- a/src/Chapter06/Listing06.53.DeclaringAFieldAsReadonly.cs +++ b/src/Chapter06/Listing06.53.DeclaringAFieldAsReadonly.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_53 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_53; + +#region INCLUDE +public class Employee { - #region INCLUDE - public class Employee + public Employee(int id) { - public Employee(int id) - { - _Id = id; - } + _Id = id; + } - // ... + // ... - #region HIGHLIGHT - private readonly int _Id; - #endregion HIGHLIGHT - public int Id - { - get { return _Id; } - } + #region HIGHLIGHT + private readonly int _Id; + #endregion HIGHLIGHT + public int Id + { + get { return _Id; } + } - #if COMPILEERROR // EXCLUDE - // Error: A readonly field cannot be assigned to (except - // in a constructor or a variable initializer) - public void SetId(int id) => - _Id = id; - #endif // COMPILEERROR // EXCLUDE + #if COMPILEERROR // EXCLUDE + // Error: A readonly field cannot be assigned to (except + // in a constructor or a variable initializer) + public void SetId(int id) => + _Id = id; + #endif // COMPILEERROR // EXCLUDE - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.54.DeclaringAReadOnlyAutomaticallyImplementedProperty.cs b/src/Chapter06/Listing06.54.DeclaringAReadOnlyAutomaticallyImplementedProperty.cs index ac7b64324..32a157117 100644 --- a/src/Chapter06/Listing06.54.DeclaringAReadOnlyAutomaticallyImplementedProperty.cs +++ b/src/Chapter06/Listing06.54.DeclaringAReadOnlyAutomaticallyImplementedProperty.cs @@ -1,78 +1,76 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_54 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_54; + +using System; + +class CommonGuid { - using System; + public static readonly Guid ComIUnknownGuid = + new("00000000-0000-0000-C000-000000000046"); + public static readonly Guid ComIClassFactoryGuid = + new("00000001-0000-0000-C000-000000000046"); + public static readonly Guid ComIDispatchGuid = + new("00020400-0000-0000-C000-000000000046"); + public static readonly Guid ComITypeInfoGuid = + new("00020401-0000-0000-C000-000000000046"); + // ... +} - class CommonGuid +public class Program +{ + public static void Main() { - public static readonly Guid ComIUnknownGuid = - new("00000000-0000-0000-C000-000000000046"); - public static readonly Guid ComIClassFactoryGuid = - new("00000001-0000-0000-C000-000000000046"); - public static readonly Guid ComIDispatchGuid = - new("00020400-0000-0000-C000-000000000046"); - public static readonly Guid ComITypeInfoGuid = - new("00020401-0000-0000-C000-000000000046"); - // ... + // Note: board.Cells does not require initialization + TicTacToeBoard board = new(); + Console.WriteLine(board.Cells); } +} - public class Program - { - public static void Main() - { - // Note: board.Cells does not require initialization - TicTacToeBoard board = new(); - Console.WriteLine(board.Cells); - } - } +#region INCLUDE +class TicTacToeBoard +{ + // Set both player's initial board to all false (blank) + // | | | | + // ---+---+--- ---+---+--- + // | | | | + // ---+---+--- ---+---+--- + // | | | | + // Player 1 - X Player 2 - O + #region HIGHLIGHT + public bool[,,] Cells { get; } = new bool[2, 3, 3]; + #endregion HIGHLIGHT + // Error: The property Cells cannot + // be assigned to because it is read-only + // public void SetCells(bool[,,] value) => + // _Cells = new bool[2, 3, 3]; + + // ... +} +#endregion INCLUDE - #region INCLUDE - class TicTacToeBoard +class TicTacToeBoardPreCSharp5 +{ + public TicTacToeBoardPreCSharp5() { // Set both player's initial board to all false (blank) - // | | | | - // ---+---+--- ---+---+--- - // | | | | - // ---+---+--- ---+---+--- - // | | | | - // Player 1 - X Player 2 - O - #region HIGHLIGHT - public bool[,,] Cells { get; } = new bool[2, 3, 3]; - #endregion HIGHLIGHT - // Error: The property Cells cannot - // be assigned to because it is read-only - // public void SetCells(bool[,,] value) => - // _Cells = new bool[2, 3, 3]; - - // ... + // | | + // ---+---+--- + // | | + // ---+---+--- + // | | + _Cells = new bool[2, 3, 3]; } - #endregion INCLUDE - - class TicTacToeBoardPreCSharp5 - { - public TicTacToeBoardPreCSharp5() - { - // Set both player's initial board to all false (blank) - // | | - // ---+---+--- - // | | - // ---+---+--- - // | | - _Cells = new bool[2, 3, 3]; - } - private readonly bool[,,] _Cells; + private readonly bool[,,] _Cells; - public bool[,,] Cells - { - get { return _Cells; } - } - - // Error: A readonly field cannot be assigned to(except - // in a constructor or a variable initializer) - // public void SetCells(bool[,,] value) => - // Cells = new bool[2, 3, 3]; - - // ... + public bool[,,] Cells + { + get { return _Cells; } } + // Error: A readonly field cannot be assigned to(except + // in a constructor or a variable initializer) + // public void SetCells(bool[,,] value) => + // Cells = new bool[2, 3, 3]; + + // ... } diff --git a/src/Chapter06/Listing06.55.DefiningANestedClass.cs b/src/Chapter06/Listing06.55.DefiningANestedClass.cs index 59e1361ea..3abc0927d 100644 --- a/src/Chapter06/Listing06.55.DefiningANestedClass.cs +++ b/src/Chapter06/Listing06.55.DefiningANestedClass.cs @@ -1,81 +1,80 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_55 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_55; + +using System; - #region INCLUDE - // CommandLine is nested within program - #region HIGHLIGHT - public class Program +#region INCLUDE +// CommandLine is nested within program +#region HIGHLIGHT +public class Program +{ + // Define a nested class for processing the command line + private class CommandLine { - // Define a nested class for processing the command line - private class CommandLine +#endregion HIGHLIGHT + public CommandLine(string[] arguments) { - #endregion HIGHLIGHT - public CommandLine(string[] arguments) + for(int argumentCounter = 0; + argumentCounter < arguments.Length; + argumentCounter++) { - for(int argumentCounter = 0; - argumentCounter < arguments.Length; - argumentCounter++) + switch(argumentCounter) { - switch(argumentCounter) - { - case 0: - Action = arguments[0].ToLower(); - break; - case 1: - Id = arguments[1]; - break; - case 2: - FirstName = arguments[2]; - break; - case 3: - LastName = arguments[3]; - break; - } + case 0: + Action = arguments[0].ToLower(); + break; + case 1: + Id = arguments[1]; + break; + case 2: + FirstName = arguments[2]; + break; + case 3: + LastName = arguments[3]; + break; } } - public string? Action { get; } - public string? Id { get; } - public string? FirstName { get; } - public string? LastName { get; } } + public string? Action { get; } + public string? Id { get; } + public string? FirstName { get; } + public string? LastName { get; } + } - public static void Main(string[] args) - { - #region HIGHLIGHT - CommandLine commandLine = new(args); - #endregion HIGHLIGHT + public static void Main(string[] args) + { + #region HIGHLIGHT + CommandLine commandLine = new(args); + #endregion HIGHLIGHT - // Error handling intentionaly missing for elucidation. + // Error handling intentionaly missing for elucidation. - switch (commandLine.Action) - { - case "new": - // Create a new employee - #region EXCLUDE - Console.WriteLine("'Creating' a new Employee."); - #endregion EXCLUDE - break; - case "update": - // Update an existing employee's data - #region EXCLUDE - Console.WriteLine("'Updating' a new Employee."); - #endregion EXCLUDE - break; - case "delete": - // Remove an existing employee's file - #region EXCLUDE - Console.WriteLine("'Removing' a new Employee."); - #endregion EXCLUDE - break; - default: - Console.WriteLine( - "Employee.exe " + - "new|update|delete " + - " [firstname] [lastname]"); - break; - } + switch (commandLine.Action) + { + case "new": + // Create a new employee + #region EXCLUDE + Console.WriteLine("'Creating' a new Employee."); + #endregion EXCLUDE + break; + case "update": + // Update an existing employee's data + #region EXCLUDE + Console.WriteLine("'Updating' a new Employee."); + #endregion EXCLUDE + break; + case "delete": + // Remove an existing employee's file + #region EXCLUDE + Console.WriteLine("'Removing' a new Employee."); + #endregion EXCLUDE + break; + default: + Console.WriteLine( + "Employee.exe " + + "new|update|delete " + + " [firstname] [lastname]"); + break; } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.56.DefiningAPartialClass.cs b/src/Chapter06/Listing06.56.DefiningAPartialClass.cs index 7f8eb5aa2..0a051f81c 100644 --- a/src/Chapter06/Listing06.56.DefiningAPartialClass.cs +++ b/src/Chapter06/Listing06.56.DefiningAPartialClass.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_56 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_56; + +#region INCLUDE +// File: Program1.cs +partial class Program { - #region INCLUDE - // File: Program1.cs - partial class Program - { - } - // File: Program2.cs - partial class Program - { - } - #endregion INCLUDE } +// File: Program2.cs +partial class Program +{ +} +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.57.DefiningANestedClassInASeperatePartialClass.cs b/src/Chapter06/Listing06.57.DefiningANestedClassInASeperatePartialClass.cs index c1d4abb86..ad8c80c16 100644 --- a/src/Chapter06/Listing06.57.DefiningANestedClassInASeperatePartialClass.cs +++ b/src/Chapter06/Listing06.57.DefiningANestedClassInASeperatePartialClass.cs @@ -1,48 +1,47 @@ // Ignored as implementation was removed for elucidation #pragma warning disable IDE0060 //Remove unused parameter -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_57 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_57; + +using System; - #region INCLUDE - // File: Program.cs - partial class Program +#region INCLUDE +// File: Program.cs +partial class Program +{ + static void Main(string[] args) { - static void Main(string[] args) - { - CommandLine commandLine = new(args); + CommandLine commandLine = new(args); - switch(commandLine.Action) - { - #region EXCLUDE - default: - break; - #endregion EXCLUDE - } + switch(commandLine.Action) + { + #region EXCLUDE + default: + break; + #endregion EXCLUDE } } +} - // File: Program+CommandLine.cs - partial class Program +// File: Program+CommandLine.cs +partial class Program +{ + // Define a nested class for processing the command line + private class CommandLine { - // Define a nested class for processing the command line - private class CommandLine + #region EXCLUDE + public CommandLine(string[] args) { - #region EXCLUDE - public CommandLine(string[] args) - { - //not implemented - } + //not implemented + } - // ... - public int Action - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - #endregion EXCLUDE + // ... + public int Action + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } } + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter06/Listing06.58.DefiningAPartialMethodToAccessItsImplementation.cs b/src/Chapter06/Listing06.58.DefiningAPartialMethodToAccessItsImplementation.cs index a201e3f15..c26e553eb 100644 --- a/src/Chapter06/Listing06.58.DefiningAPartialMethodToAccessItsImplementation.cs +++ b/src/Chapter06/Listing06.58.DefiningAPartialMethodToAccessItsImplementation.cs @@ -1,96 +1,95 @@ // Non-nullable field is uninitialized. Consider declaring as nullable. #pragma warning disable CS8618 // Pending a constructors -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_58 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter06.Listing06_58; + +using System; + +#region INCLUDE +// File: Person.Designer.cs +public partial class Person { - using System; + #region Extensibility Method Definitions + #region HIGHLIGHT + static partial void OnLastNameChanging(string value); + static partial void OnFirstNameChanging(string value); + #endregion HIGHLIGHT + #endregion Extensibility Method Definitions - #region INCLUDE - // File: Person.Designer.cs - public partial class Person + // ... + public string LastName { - #region Extensibility Method Definitions - #region HIGHLIGHT - static partial void OnLastNameChanging(string value); - static partial void OnFirstNameChanging(string value); - #endregion HIGHLIGHT - #endregion Extensibility Method Definitions - - // ... - public string LastName + get { - get - { - return _LastName; - } - set - { - if (_LastName != value) - { - #region HIGHLIGHT - OnLastNameChanging(value); - #endregion HIGHLIGHT - _LastName = value; - } - } + return _LastName; } - private string _LastName; - - // ... - public string FirstName + set { - get + if (_LastName != value) { - return _FirstName; - } - set - { - if (_FirstName != value) - { - #region HIGHLIGHT - OnFirstNameChanging(value); - #endregion HIGHLIGHT - _FirstName = value; - } + #region HIGHLIGHT + OnLastNameChanging(value); + #endregion HIGHLIGHT + _LastName = value; } } - private string _FirstName; - - public partial string GetName(); } + private string _LastName; - // File: Person.cs - partial class Person + // ... + public string FirstName { - static partial void OnLastNameChanging(string value) + get { - value = value ?? - throw new ArgumentNullException(nameof(value)); - - if (value.Trim().Length == 0) + return _FirstName; + } + set + { + if (_FirstName != value) { - throw new ArgumentException( - $"{nameof(LastName)} cannot be empty.", - nameof(value)); + #region HIGHLIGHT + OnFirstNameChanging(value); + #endregion HIGHLIGHT + _FirstName = value; } } + } + private string _FirstName; - #region EXCLUDE - static partial void OnFirstNameChanging(string value) - { - value = value ?? - throw new ArgumentNullException(nameof(value)); + public partial string GetName(); +} - if (value.Trim().Length == 0) - { - throw new ArgumentException( - $"{nameof(FirstName)} cannot be empty.", - nameof(value)); - } +// File: Person.cs +partial class Person +{ + static partial void OnLastNameChanging(string value) + { + value = value ?? + throw new ArgumentNullException(nameof(value)); + + if (value.Trim().Length == 0) + { + throw new ArgumentException( + $"{nameof(LastName)} cannot be empty.", + nameof(value)); } - #endregion EXCLUDE + } + + #region EXCLUDE + static partial void OnFirstNameChanging(string value) + { + value = value ?? + throw new ArgumentNullException(nameof(value)); - public partial string GetName() => $"{FirstName} {LastName}"; + if (value.Trim().Length == 0) + { + throw new ArgumentException( + $"{nameof(FirstName)} cannot be empty.", + nameof(value)); + } } - #endregion INCLUDE + #endregion EXCLUDE + + public partial string GetName() => $"{FirstName} {LastName}"; } +#endregion INCLUDE diff --git a/src/Chapter10/Employee.cs b/src/Chapter10/Employee.cs index 90be0914a..235073788 100644 --- a/src/Chapter10/Employee.cs +++ b/src/Chapter10/Employee.cs @@ -1,6 +1,5 @@ -namespace Chapter10 +namespace Chapter10; + +class Employee { - class Employee - { - } } diff --git a/src/Chapter10/Listing10.01.ImplementingTheEqualsAndNotEqualsOperators.cs b/src/Chapter10/Listing10.01.ImplementingTheEqualsAndNotEqualsOperators.cs index 5df0b144e..cd9e88267 100644 --- a/src/Chapter10/Listing10.01.ImplementingTheEqualsAndNotEqualsOperators.cs +++ b/src/Chapter10/Listing10.01.ImplementingTheEqualsAndNotEqualsOperators.cs @@ -1,95 +1,94 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_01; + +#region INCLUDE +public sealed class ProductSerialNumber { - #region INCLUDE - public sealed class ProductSerialNumber + #region EXCLUDE + public ProductSerialNumber( + string productSeries, int model, long id) { - #region EXCLUDE - public ProductSerialNumber( - string productSeries, int model, long id) - { - ProductSeries = productSeries; - Model = model; - Id = id; - } + ProductSeries = productSeries; + Model = model; + Id = id; + } + + public string ProductSeries { get; } + public int Model { get; } + public long Id { get; } - public string ProductSeries { get; } - public int Model { get; } - public long Id { get; } + public override int GetHashCode() + { + int hashCode = ProductSeries.GetHashCode(); + hashCode ^= Model; // Xor (eXclusive OR) + hashCode ^= Id.GetHashCode(); // Xor (eXclusive OR) + return hashCode; + } - public override int GetHashCode() + public override bool Equals(object? obj) + { + if(obj is null) { - int hashCode = ProductSeries.GetHashCode(); - hashCode ^= Model; // Xor (eXclusive OR) - hashCode ^= Id.GetHashCode(); // Xor (eXclusive OR) - return hashCode; + return false; } - - public override bool Equals(object? obj) + if(ReferenceEquals(this, obj)) { - if(obj is null) - { - return false; - } - if(ReferenceEquals(this, obj)) - { - return true; - } - if(this.GetType() != obj.GetType()) - { - return false; - } - return Equals((ProductSerialNumber)obj); + return true; } - - public bool Equals(ProductSerialNumber? obj) + if(this.GetType() != obj.GetType()) { - // STEP 3: Possibly check for equivalent hash codes - // if (this.GetHashCode() != obj.GetHashCode()) - // { - // return false; - // } - - // STEP 4: Check base.Equals if base overrides Equals() - // System.Diagnostics.Debug.Assert( - // base.GetType() != typeof(object)); - // if ( base.Equals(obj) ) - // { - // return false; - // } - - // STEP 1: Check for null - return ((obj is not null) - // STEP 5: Compare identifying fields for equality. - && (ProductSeries == obj.ProductSeries) && - (Model == obj.Model) && - (Id == obj.Id)); + return false; } - #endregion EXCLUDE + return Equals((ProductSerialNumber)obj); + } - public static bool operator ==( - ProductSerialNumber leftHandSide, - ProductSerialNumber rightHandSide) - { + public bool Equals(ProductSerialNumber? obj) + { + // STEP 3: Possibly check for equivalent hash codes + // if (this.GetHashCode() != obj.GetHashCode()) + // { + // return false; + // } - // Check if leftHandSide is null - // (operator == would be recursive) - if(leftHandSide is null) - { - // Return true if rightHandSide is also null - // and false otherwise - return rightHandSide is null; - } + // STEP 4: Check base.Equals if base overrides Equals() + // System.Diagnostics.Debug.Assert( + // base.GetType() != typeof(object)); + // if ( base.Equals(obj) ) + // { + // return false; + // } - return (leftHandSide.Equals(rightHandSide)); - } + // STEP 1: Check for null + return ((obj is not null) + // STEP 5: Compare identifying fields for equality. + && (ProductSeries == obj.ProductSeries) && + (Model == obj.Model) && + (Id == obj.Id)); + } + #endregion EXCLUDE - public static bool operator !=( - ProductSerialNumber leftHandSide, - ProductSerialNumber rightHandSide) + public static bool operator ==( + ProductSerialNumber leftHandSide, + ProductSerialNumber rightHandSide) + { + + // Check if leftHandSide is null + // (operator == would be recursive) + if(leftHandSide is null) { - return !(leftHandSide == rightHandSide); + // Return true if rightHandSide is also null + // and false otherwise + return rightHandSide is null; } + + return (leftHandSide.Equals(rightHandSide)); + } + + public static bool operator !=( + ProductSerialNumber leftHandSide, + ProductSerialNumber rightHandSide) + { + return !(leftHandSide == rightHandSide); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.02.AddingAnOperator.cs b/src/Chapter10/Listing10.02.AddingAnOperator.cs index ca7127596..7b6caba31 100644 --- a/src/Chapter10/Listing10.02.AddingAnOperator.cs +++ b/src/Chapter10/Listing10.02.AddingAnOperator.cs @@ -1,198 +1,197 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_02; + +#region INCLUDE +public readonly struct Arc { - #region INCLUDE - public readonly struct Arc + public Arc( + Longitude longitudeDifference, + Latitude latitudeDifference) { - public Arc( - Longitude longitudeDifference, - Latitude latitudeDifference) - { - LongitudeDifference = longitudeDifference; - LatitudeDifference = latitudeDifference; - } + LongitudeDifference = longitudeDifference; + LatitudeDifference = latitudeDifference; + } - public Longitude LongitudeDifference { get; } - public Latitude LatitudeDifference { get; } + public Longitude LongitudeDifference { get; } + public Latitude LatitudeDifference { get; } +} + +public readonly struct Coordinate +{ + #region EXCLUDE + public Coordinate(Longitude longitude, Latitude latitude) + { + Longitude = longitude; + Latitude = latitude; } + #endregion EXCLUDE + public static Coordinate operator +( + Coordinate source, Arc arc) + { + Coordinate result = new( + new Longitude( + source.Longitude + arc.LongitudeDifference), + new Latitude( + source.Latitude + arc.LatitudeDifference)); + return result; + } + #region EXCLUDE - public readonly struct Coordinate + public static Coordinate operator -( + Coordinate source, Arc arc) { - #region EXCLUDE - public Coordinate(Longitude longitude, Latitude latitude) - { - Longitude = longitude; - Latitude = latitude; - } - #endregion EXCLUDE - public static Coordinate operator +( - Coordinate source, Arc arc) - { - Coordinate result = new( - new Longitude( - source.Longitude + arc.LongitudeDifference), - new Latitude( - source.Latitude + arc.LatitudeDifference)); - return result; - } - #region EXCLUDE + Coordinate result = new( + new Longitude( + source.Longitude - arc.LongitudeDifference), + new Latitude( + source.Latitude - arc.LatitudeDifference)); + return result; + } - public static Coordinate operator -( - Coordinate source, Arc arc) - { - Coordinate result = new( - new Longitude( - source.Longitude - arc.LongitudeDifference), - new Latitude( - source.Latitude - arc.LatitudeDifference)); - return result; - } + public static bool operator ==( + Coordinate leftHandSide, + Coordinate rightHandSide) + { - public static bool operator ==( - Coordinate leftHandSide, - Coordinate rightHandSide) - { + // There is no need to check of null in this + // case because Coordinate is a valye type. + return (leftHandSide.Equals(rightHandSide)); + } - // There is no need to check of null in this - // case because Coordinate is a valye type. - return (leftHandSide.Equals(rightHandSide)); - } + public static bool operator !=( + Coordinate leftHandSide, + Coordinate rightHandSide) + { + return !(leftHandSide == rightHandSide); + } - public static bool operator !=( - Coordinate leftHandSide, - Coordinate rightHandSide) + public override bool Equals(object? obj) + { + // STEP 1: Check for null + if (obj is null) { - return !(leftHandSide == rightHandSide); + return false; } - - public override bool Equals(object? obj) + // STEP 3: equivalent data types + if (this.GetType() != obj.GetType()) { - // STEP 1: Check for null - if (obj is null) - { - return false; - } - // STEP 3: equivalent data types - if (this.GetType() != obj.GetType()) - { - return false; - } - return Equals((Coordinate)obj); + return false; } + return Equals((Coordinate)obj); + } - public bool Equals(Coordinate obj) - { - // STEP 1: Check for null if a reference type - // (e.g., a reference type) - // if (obj == null) - // { - // return false; - // } - - // STEP 2: Check for ReferenceEquals if this - // is a reference type - // if ( ReferenceEquals(this, obj)) - // { - // return true; - // } - - // STEP 4: Possibly check for equivalent hash codes - // if (this.GetHashCode() != obj.GetHashCode()) - // { - // return false; - // } - - // STEP 5: Check base.Equals if base overrides Equals() - // System.Diagnostics.Debug.Assert( - // base.GetType() != typeof(object) ); - // if ( !base.Equals(obj) ) - // { - // return false; - // } - - // STEP 6: Compare identifying fields for equality - // using an overload of Equals on Longitude - return ((Longitude.Equals(obj.Longitude)) && - (Latitude.Equals(obj.Latitude))); - } + public bool Equals(Coordinate obj) + { + // STEP 1: Check for null if a reference type + // (e.g., a reference type) + // if (obj == null) + // { + // return false; + // } + + // STEP 2: Check for ReferenceEquals if this + // is a reference type + // if ( ReferenceEquals(this, obj)) + // { + // return true; + // } + + // STEP 4: Possibly check for equivalent hash codes + // if (this.GetHashCode() != obj.GetHashCode()) + // { + // return false; + // } + + // STEP 5: Check base.Equals if base overrides Equals() + // System.Diagnostics.Debug.Assert( + // base.GetType() != typeof(object) ); + // if ( !base.Equals(obj) ) + // { + // return false; + // } + + // STEP 6: Compare identifying fields for equality + // using an overload of Equals on Longitude + return ((Longitude.Equals(obj.Longitude)) && + (Latitude.Equals(obj.Latitude))); + } - // STEP 7: Override GetHashCode - public override int GetHashCode() - { - int hashCode = Longitude.GetHashCode(); - hashCode ^= Latitude.GetHashCode(); // Xor (eXclusive OR) - return hashCode; - } + // STEP 7: Override GetHashCode + public override int GetHashCode() + { + int hashCode = Longitude.GetHashCode(); + hashCode ^= Latitude.GetHashCode(); // Xor (eXclusive OR) + return hashCode; + } - public Longitude Longitude { get; } - public Latitude Latitude { get; } + public Longitude Longitude { get; } + public Latitude Latitude { get; } - public override string ToString() - { - return string.Format("{0}° {1}' 0 E {2}° {3}' 0 N", Longitude.Degrees, Longitude.Minutes, Latitude.Degrees, Latitude.Minutes); - } - #endregion EXCLUDE + public override string ToString() + { + return string.Format("{0}° {1}' 0 E {2}° {3}' 0 N", Longitude.Degrees, Longitude.Minutes, Latitude.Degrees, Latitude.Minutes); } - #endregion INCLUDE + #endregion EXCLUDE +} +#endregion INCLUDE - public readonly struct Longitude +public readonly struct Longitude +{ + public Longitude(int degrees, int minutes) { - public Longitude(int degrees, int minutes) - { - Degrees = degrees; - Minutes = minutes; - } + Degrees = degrees; + Minutes = minutes; + } - public Longitude(int degrees) - : this(degrees, 0) { } + public Longitude(int degrees) + : this(degrees, 0) { } - public Longitude(Longitude longitude) - : this(longitude.Degrees, longitude.Minutes) { } + public Longitude(Longitude longitude) + : this(longitude.Degrees, longitude.Minutes) { } - public int Degrees { get; } - public int Minutes { get; } + public int Degrees { get; } + public int Minutes { get; } - public static Longitude operator +(Longitude leftHandSide, Longitude rightHandSide) - { - return new Longitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); - } + public static Longitude operator +(Longitude leftHandSide, Longitude rightHandSide) + { + return new Longitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); + } - public static Longitude operator -(Longitude leftHandSide, Longitude rightHandSide) - { - return new Longitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); - } + public static Longitude operator -(Longitude leftHandSide, Longitude rightHandSide) + { + return new Longitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); } +} - public readonly struct Latitude +public readonly struct Latitude +{ + public Latitude(int degrees, int minutes) { - public Latitude(int degrees, int minutes) - { - Degrees = degrees; - Minutes = minutes; - } + Degrees = degrees; + Minutes = minutes; + } - public Latitude(int degrees) - : this(degrees, 0) { } + public Latitude(int degrees) + : this(degrees, 0) { } - public Latitude(Latitude Latitude) - : this(Latitude.Degrees, Latitude.Minutes) { } + public Latitude(Latitude Latitude) + : this(Latitude.Degrees, Latitude.Minutes) { } - public int Degrees { get; } - public int Minutes { get; } + public int Degrees { get; } + public int Minutes { get; } - public static Latitude operator +(Latitude leftHandSide, Latitude rightHandSide) - { - return new Latitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); - } + public static Latitude operator +(Latitude leftHandSide, Latitude rightHandSide) + { + return new Latitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); + } - public static Latitude operator -(Latitude leftHandSide, Latitude rightHandSide) - { - return new Latitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); - } + public static Latitude operator -(Latitude leftHandSide, Latitude rightHandSide) + { + return new Latitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); } } diff --git a/src/Chapter10/Listing10.03.CallingTheMinusAndPlusBinaryOperators.cs b/src/Chapter10/Listing10.03.CallingTheMinusAndPlusBinaryOperators.cs index e9f380711..70842f803 100644 --- a/src/Chapter10/Listing10.03.CallingTheMinusAndPlusBinaryOperators.cs +++ b/src/Chapter10/Listing10.03.CallingTheMinusAndPlusBinaryOperators.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_03; + +using System; +using Listing10_02; +#region INCLUDE +// Use compound assignment suppressed for demonstration purposes +#pragma warning disable IDE0054 +public class Program { - using System; - using Listing10_02; - #region INCLUDE - // Use compound assignment suppressed for demonstration purposes - #pragma warning disable IDE0054 - public class Program + public static void Main() { - public static void Main() - { - Coordinate coordinate1, coordinate2; - coordinate1 = new Coordinate( - new Longitude(48, 52), new Latitude(-2, -20)); - Arc arc = new(new Longitude(3), new Latitude(1)); + Coordinate coordinate1, coordinate2; + coordinate1 = new Coordinate( + new Longitude(48, 52), new Latitude(-2, -20)); + Arc arc = new(new Longitude(3), new Latitude(1)); - coordinate2 = coordinate1 + arc; - Console.WriteLine(coordinate2); + coordinate2 = coordinate1 + arc; + Console.WriteLine(coordinate2); - coordinate2 = coordinate2 - arc; - Console.WriteLine(coordinate2); + coordinate2 = coordinate2 - arc; + Console.WriteLine(coordinate2); - coordinate2 += arc; - Console.WriteLine(coordinate2); - } + coordinate2 += arc; + Console.WriteLine(coordinate2); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.04.OverloadingTheMinusAndPlusUnaryOperators.cs b/src/Chapter10/Listing10.04.OverloadingTheMinusAndPlusUnaryOperators.cs index cfa6fb51a..97fa43733 100644 --- a/src/Chapter10/Listing10.04.OverloadingTheMinusAndPlusUnaryOperators.cs +++ b/src/Chapter10/Listing10.04.OverloadingTheMinusAndPlusUnaryOperators.cs @@ -1,281 +1,280 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_04; + +public readonly struct Coordinate { - public readonly struct Coordinate + public Coordinate(Longitude longitude, Latitude latitude) { - public Coordinate(Longitude longitude, Latitude latitude) - { - _Longitude = longitude; - _Latitude = latitude; - } + _Longitude = longitude; + _Latitude = latitude; + } - public static Coordinate operator +( - Coordinate source, Arc arc) - { - Coordinate result = new( - new Longitude( - source.Longitude + arc.LongitudeDifference), - new Latitude( - source.Latitude + arc.LatitudeDifference)); - return result; - } + public static Coordinate operator +( + Coordinate source, Arc arc) + { + Coordinate result = new( + new Longitude( + source.Longitude + arc.LongitudeDifference), + new Latitude( + source.Latitude + arc.LatitudeDifference)); + return result; + } - public static Coordinate operator -( - Coordinate source, Arc arc) - { - Coordinate result = new( - new Longitude( - source.Longitude - arc.LongitudeDifference), - new Latitude( - source.Latitude - arc.LatitudeDifference)); - return result; - } + public static Coordinate operator -( + Coordinate source, Arc arc) + { + Coordinate result = new( + new Longitude( + source.Longitude - arc.LongitudeDifference), + new Latitude( + source.Latitude - arc.LatitudeDifference)); + return result; + } - public static bool operator ==( - Coordinate leftHandSide, - Coordinate rightHandSide) - { + public static bool operator ==( + Coordinate leftHandSide, + Coordinate rightHandSide) + { - // There is no need to check of null in this - // case because Coordinate is a valye type. - return (leftHandSide.Equals(rightHandSide)); - } + // There is no need to check of null in this + // case because Coordinate is a valye type. + return (leftHandSide.Equals(rightHandSide)); + } - public static bool operator !=( - Coordinate leftHandSide, - Coordinate rightHandSide) - { - return !(leftHandSide == rightHandSide); - } + public static bool operator !=( + Coordinate leftHandSide, + Coordinate rightHandSide) + { + return !(leftHandSide == rightHandSide); + } - public override bool Equals(object? obj) + public override bool Equals(object? obj) + { + // STEP 1: Check for null + if(obj is null) { - // STEP 1: Check for null - if(obj is null) - { - return false; - } - // STEP 3: equivalent data types - if(this.GetType() != obj.GetType()) - { - return false; - } - return Equals((Coordinate)obj); + return false; } - - public bool Equals(Coordinate obj) + // STEP 3: equivalent data types + if(this.GetType() != obj.GetType()) { - // STEP 1: Check for null if a reference type - // (e.g., a reference type) - // if (obj == null) - // { - // return false; - // } - - // STEP 2: Check for ReferenceEquals if this - // is a reference type - // if ( ReferenceEquals(this, obj)) - // { - // return true; - // } - - // STEP 4: Possibly check for equivalent hash codes - // if (this.GetHashCode() != obj.GetHashCode()) - // { - // return false; - // } - - // STEP 5: Check base.Equals if base overrides Equals() - // System.Diagnostics.Debug.Assert( - // base.GetType() != typeof(object) ); - // if ( !base.Equals(obj) ) - // { - // return false; - // } - - // STEP 6: Compare identifying fields for equality - // using an overload of Equals on Longitude - return ((Longitude.Equals(obj.Longitude)) && - (Latitude.Equals(obj.Latitude))); + return false; } + return Equals((Coordinate)obj); + } - // STEP 7: Override GetHashCode. - public override int GetHashCode() - { - int hashCode = Longitude.GetHashCode(); - hashCode ^= Latitude.GetHashCode(); // Xor (eXclusive OR) - return hashCode; - } + public bool Equals(Coordinate obj) + { + // STEP 1: Check for null if a reference type + // (e.g., a reference type) + // if (obj == null) + // { + // return false; + // } + + // STEP 2: Check for ReferenceEquals if this + // is a reference type + // if ( ReferenceEquals(this, obj)) + // { + // return true; + // } + + // STEP 4: Possibly check for equivalent hash codes + // if (this.GetHashCode() != obj.GetHashCode()) + // { + // return false; + // } + + // STEP 5: Check base.Equals if base overrides Equals() + // System.Diagnostics.Debug.Assert( + // base.GetType() != typeof(object) ); + // if ( !base.Equals(obj) ) + // { + // return false; + // } + + // STEP 6: Compare identifying fields for equality + // using an overload of Equals on Longitude + return ((Longitude.Equals(obj.Longitude)) && + (Latitude.Equals(obj.Latitude))); + } - public Longitude Longitude { get { return _Longitude; } } - private readonly Longitude _Longitude; + // STEP 7: Override GetHashCode. + public override int GetHashCode() + { + int hashCode = Longitude.GetHashCode(); + hashCode ^= Latitude.GetHashCode(); // Xor (eXclusive OR) + return hashCode; + } - public Latitude Latitude { get { return _Latitude; } } - private readonly Latitude _Latitude; + public Longitude Longitude { get { return _Longitude; } } + private readonly Longitude _Longitude; - public override string ToString() - { - return string.Format("{0}° {1}' 0 E {2}° {3}' 0 N", Longitude.Degrees, Longitude.Minutes, Latitude.Degrees, Latitude.Minutes); - } + public Latitude Latitude { get { return _Latitude; } } + private readonly Latitude _Latitude; + public override string ToString() + { + return string.Format("{0}° {1}' 0 E {2}° {3}' 0 N", Longitude.Degrees, Longitude.Minutes, Latitude.Degrees, Latitude.Minutes); } - #region INCLUDE - public struct Latitude +} + +#region INCLUDE +public struct Latitude +{ + #region EXCLUDE + public Latitude(int degrees, int minutes) { - #region EXCLUDE - public Latitude(int degrees, int minutes) - { - _Degrees = degrees; - _Minutes = minutes; - } + _Degrees = degrees; + _Minutes = minutes; + } - public Latitude(int degrees) - : this(degrees, 0) { } + public Latitude(int degrees) + : this(degrees, 0) { } - public Latitude(Latitude Latitude) - : this(Latitude.Degrees, Latitude.Minutes) { } + public Latitude(Latitude Latitude) + : this(Latitude.Degrees, Latitude.Minutes) { } - public int Degrees - { - get { return _Degrees; } - set { _Degrees = value; } - } - private int _Degrees; + public int Degrees + { + get { return _Degrees; } + set { _Degrees = value; } + } + private int _Degrees; - public int Minutes - { - get { return _Minutes; } - set { _Minutes = value; } - } - private int _Minutes; + public int Minutes + { + get { return _Minutes; } + set { _Minutes = value; } + } + private int _Minutes; - // UNARY - #endregion EXCLUDE - #region HIGHLIGHT - public static Latitude operator -(Latitude latitude) - { - return new Latitude(-latitude.Degrees); - } + // UNARY + #endregion EXCLUDE + #region HIGHLIGHT + public static Latitude operator -(Latitude latitude) + { + return new Latitude(-latitude.Degrees); + } - public static Latitude operator +(Latitude latitude) - { - return latitude; - } - #endregion HIGHLIGHT + public static Latitude operator +(Latitude latitude) + { + return latitude; + } + #endregion HIGHLIGHT - #region EXCLUDE - public static Latitude operator +(Latitude leftHandSide, Latitude rightHandSide) - { - return new Latitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); - } + #region EXCLUDE + public static Latitude operator +(Latitude leftHandSide, Latitude rightHandSide) + { + return new Latitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); + } - public static Latitude operator -(Latitude leftHandSide, Latitude rightHandSide) - { - return new Latitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); - } - #endregion EXCLUDE + public static Latitude operator -(Latitude leftHandSide, Latitude rightHandSide) + { + return new Latitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); } + #endregion EXCLUDE +} - public struct Longitude +public struct Longitude +{ + #region EXCLUDE + public Longitude(int degrees, int minutes) { - #region EXCLUDE - public Longitude(int degrees, int minutes) - { - _Degrees = degrees; - _Minutes = minutes; - } + _Degrees = degrees; + _Minutes = minutes; + } - public Longitude(int degrees) - : this(degrees, 0) { } + public Longitude(int degrees) + : this(degrees, 0) { } - public Longitude(Longitude longitude) - : this(longitude.Degrees, longitude.Minutes) { } + public Longitude(Longitude longitude) + : this(longitude.Degrees, longitude.Minutes) { } - public int Degrees - { - get { return _Degrees; } - set { _Degrees = value; } - } - private int _Degrees; + public int Degrees + { + get { return _Degrees; } + set { _Degrees = value; } + } + private int _Degrees; - public int Minutes - { - get { return _Minutes; } - set { _Minutes = value; } - } - private int _Minutes; + public int Minutes + { + get { return _Minutes; } + set { _Minutes = value; } + } + private int _Minutes; - // UNARY - #endregion EXCLUDE - #region HIGHLIGHT - public static Longitude operator -(Longitude longitude) - { - return new Longitude(-longitude.Degrees); - } + // UNARY + #endregion EXCLUDE + #region HIGHLIGHT + public static Longitude operator -(Longitude longitude) + { + return new Longitude(-longitude.Degrees); + } - public static Longitude operator +(Longitude longitude) - { - return longitude; - } - #endregion HIGHLIGHT - #region EXCLUDE - // ---- + public static Longitude operator +(Longitude longitude) + { + return longitude; + } + #endregion HIGHLIGHT + #region EXCLUDE + // ---- - public static Longitude operator +(Longitude leftHandSide, Longitude rightHandSide) - { - return new Longitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); - } + public static Longitude operator +(Longitude leftHandSide, Longitude rightHandSide) + { + return new Longitude(leftHandSide.Degrees + rightHandSide.Degrees, leftHandSide.Minutes + rightHandSide.Minutes); + } - public static Longitude operator -(Longitude leftHandSide, Longitude rightHandSide) - { - return new Longitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); - } - #endregion EXCLUDE + public static Longitude operator -(Longitude leftHandSide, Longitude rightHandSide) + { + return new Longitude(leftHandSide.Degrees - rightHandSide.Degrees, leftHandSide.Minutes - rightHandSide.Minutes); } - public readonly struct Arc + #endregion EXCLUDE +} +public readonly struct Arc +{ + #region EXCLUDE + public Arc( + Longitude longitudeDifference, + Latitude latitudeDifference) { - #region EXCLUDE - public Arc( - Longitude longitudeDifference, - Latitude latitudeDifference) - { - _LongitudeDifference = longitudeDifference; - _LatitudeDifference = latitudeDifference; - } + _LongitudeDifference = longitudeDifference; + _LatitudeDifference = latitudeDifference; + } - public Longitude LongitudeDifference + public Longitude LongitudeDifference + { + get { - get - { - return _LongitudeDifference; - } + return _LongitudeDifference; } - private readonly Longitude _LongitudeDifference; + } + private readonly Longitude _LongitudeDifference; - public Latitude LatitudeDifference - { - get - { - return _LatitudeDifference; - } - } - private readonly Latitude _LatitudeDifference; - #endregion EXCLUDE - public static Arc operator -(Arc arc) + public Latitude LatitudeDifference + { + get { - // Uses unary – operator defined on - // Longitude and Latitude - #region HIGHLIGHT - return new Arc(-arc.LongitudeDifference, - -arc.LatitudeDifference); - #endregion HIGHLIGHT + return _LatitudeDifference; } + } + private readonly Latitude _LatitudeDifference; + #endregion EXCLUDE + public static Arc operator -(Arc arc) + { + // Uses unary – operator defined on + // Longitude and Latitude + #region HIGHLIGHT + return new Arc(-arc.LongitudeDifference, + -arc.LatitudeDifference); + #endregion HIGHLIGHT + } - public static Arc operator +(Arc arc) - { - return arc; - } + public static Arc operator +(Arc arc) + { + return arc; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.05.TrueAndFalseOperators.cs b/src/Chapter10/Listing10.05.TrueAndFalseOperators.cs index f2d99670b..ca23805b4 100644 --- a/src/Chapter10/Listing10.05.TrueAndFalseOperators.cs +++ b/src/Chapter10/Listing10.05.TrueAndFalseOperators.cs @@ -1,22 +1,21 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_05; + +public struct Example { - public struct Example + /* + #region INCLUDE + public static bool operator false(object item) { - /* - #region INCLUDE - public static bool operator false(object item) - { - #region EXCLUDE - return true; - #endregion EXCLUDE - } - public static bool operator true(object item) - { - #region EXCLUDE - return true; - #endregion EXCLUDE - } - #endregion INCLUDE - */ + #region EXCLUDE + return true; + #endregion EXCLUDE } + public static bool operator true(object item) + { + #region EXCLUDE + return true; + #endregion EXCLUDE + } + #endregion INCLUDE + */ } diff --git a/src/Chapter10/Listing10.06.ProvidingAnImplicitConversionBetweenLatitudeAndDouble.cs b/src/Chapter10/Listing10.06.ProvidingAnImplicitConversionBetweenLatitudeAndDouble.cs index 6702860ac..14ebb0abe 100644 --- a/src/Chapter10/Listing10.06.ProvidingAnImplicitConversionBetweenLatitudeAndDouble.cs +++ b/src/Chapter10/Listing10.06.ProvidingAnImplicitConversionBetweenLatitudeAndDouble.cs @@ -1,35 +1,34 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_06; + +#region INCLUDE +public readonly struct Latitude { - #region INCLUDE - public readonly struct Latitude - { - // ... + // ... - public Latitude(double decimalDegrees) - { - DecimalDegrees = Normalize(decimalDegrees); - } + public Latitude(double decimalDegrees) + { + DecimalDegrees = Normalize(decimalDegrees); + } - public double DecimalDegrees { get; } + public double DecimalDegrees { get; } - // ... + // ... - public static implicit operator double(Latitude latitude) - { - return latitude.DecimalDegrees; - } - public static implicit operator Latitude(double degrees) - { - return new Latitude(degrees); - } + public static implicit operator double(Latitude latitude) + { + return latitude.DecimalDegrees; + } + public static implicit operator Latitude(double degrees) + { + return new Latitude(degrees); + } - #region EXCLUDE - private static double Normalize(double decimalDegrees) - { - // here you would normalize the data - return decimalDegrees; - } - #endregion EXCLUDE + #region EXCLUDE + private static double Normalize(double decimalDegrees) + { + // here you would normalize the data + return decimalDegrees; } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.07.LeveragingADifferentLibrary.cs b/src/Chapter10/Listing10.07.LeveragingADifferentLibrary.cs index 839c1d99d..44291e32e 100644 --- a/src/Chapter10/Listing10.07.LeveragingADifferentLibrary.cs +++ b/src/Chapter10/Listing10.07.LeveragingADifferentLibrary.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_07 -{ - using Microsoft.Extensions.Logging; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_07; + +using Microsoft.Extensions.Logging; - #region INCLUDE - public sealed class Program +#region INCLUDE +public sealed class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) - { - using ILoggerFactory loggerFactory = - LoggerFactory.Create(builder => - builder.AddConsole().AddDebug()); + using ILoggerFactory loggerFactory = + LoggerFactory.Create(builder => + builder.AddConsole().AddDebug()); - ILogger logger = loggerFactory.CreateLogger(); + ILogger logger = loggerFactory.CreateLogger(); - logger.LogInformation($@"Hospital Emergency Codes: = '{ - string.Join("', '", args)}'"); - // ... + logger.LogInformation($@"Hospital Emergency Codes: = '{ + string.Join("', '", args)}'"); + // ... - logger.LogWarning("This is a test of the emergency..."); - // ... - } + logger.LogWarning("This is a test of the emergency..."); + // ... } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.08.MakingTypesAvailableExternally.cs b/src/Chapter10/Listing10.08.MakingTypesAvailableExternally.cs index 7359568dc..68801f826 100644 --- a/src/Chapter10/Listing10.08.MakingTypesAvailableExternally.cs +++ b/src/Chapter10/Listing10.08.MakingTypesAvailableExternally.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_08; + +#region INCLUDE +public struct Coordinate { - #region INCLUDE - public struct Coordinate - { - // ... - } + // ... +} - public struct Latitude - { - // ... - } +public struct Latitude +{ + // ... +} - public struct Longitude - { - // ... - } +public struct Longitude +{ + // ... +} - public struct Arc - { - // ... - } - #endregion INCLUDE +public struct Arc +{ + // ... } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.14.WeakReferences.cs b/src/Chapter10/Listing10.14.WeakReferences.cs index ff1d077c3..100fe23e8 100644 --- a/src/Chapter10/Listing10.14.WeakReferences.cs +++ b/src/Chapter10/Listing10.14.WeakReferences.cs @@ -1,110 +1,108 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_14 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_14; - public class LazyWeakReference - where T: class - { - private Lazy> WeakReference { get; } - private Func ValueFactory { get; } - public LazyWeakReference(Func valueFactory) - { - WeakReference = - new Lazy>(() => new WeakReference(valueFactory())); - ValueFactory = valueFactory; - } +using System; - public T Target - { - get - { - T value; - if(WeakReference.Value.TryGetTarget(out T? target)) - { - value = target; - } - else - { - value = ValueFactory(); - WeakReference.Value.SetTarget(value); - } - return value; - } - } +public class LazyWeakReference + where T: class +{ + private Lazy> WeakReference { get; } + private Func ValueFactory { get; } + public LazyWeakReference(Func valueFactory) + { + WeakReference = + new Lazy>(() => new WeakReference(valueFactory())); + ValueFactory = valueFactory; } - #region INCLUDE - public static class ByteArrayDataSource + public T Target { - static private byte[] LoadData() + get { - // Imagine a much lager number - byte[] data = new byte[1000]; - // Load data - // ... - return data; - } - - static private WeakReference? Data { get; set; } - - static public byte[] GetData() - { - byte[]? target; - if (Data is null) - { - target = LoadData(); - Data = new WeakReference(target); - return target; - } - else if (Data.TryGetTarget(out target)) + T value; + if(WeakReference.Value.TryGetTarget(out T? target)) { - return target; + value = target; } else { - // Reload the data and assign it (creating a strong - // reference) before setting WeakReference's Target - // and returning it. - target = LoadData(); - Data.SetTarget(target); - return target; + value = ValueFactory(); + WeakReference.Value.SetTarget(value); } + return value; } } +} + +#region INCLUDE +public static class ByteArrayDataSource +{ + static private byte[] LoadData() + { + // Imagine a much lager number + byte[] data = new byte[1000]; + // Load data + // ... + return data; + } - // ... - #endregion INCLUDE + static private WeakReference? Data { get; set; } - public class ObjectDataSource + static public byte[] GetData() { - private readonly WeakReference Data = new(null); - public void ClearReference() + byte[]? target; + if (Data is null) { - Data.Target = null; + target = LoadData(); + Data = new WeakReference(target); + return target; } - - public byte[] GetData() + else if (Data.TryGetTarget(out target)) + { + return target; + } + else { - byte[]? data = (byte[]?)Data.Target; + // Reload the data and assign it (creating a strong + // reference) before setting WeakReference's Target + // and returning it. + target = LoadData(); + Data.SetTarget(target); + return target; + } + } +} - if (data is not null) - { - return data; - } - else - { - // Imagine a much lager number - data = new byte[1000]; +// ... +#endregion INCLUDE - // Load data - // ... +public class ObjectDataSource +{ + private readonly WeakReference Data = new(null); + public void ClearReference() + { + Data.Target = null; + } - // Create a weak reference - // to data for use later - Data.Target = data; - } + public byte[] GetData() + { + byte[]? data = (byte[]?)Data.Target; + + if (data is not null) + { return data; } - } + else + { + // Imagine a much lager number + data = new byte[1000]; + + // Load data + // ... + // Create a weak reference + // to data for use later + Data.Target = data; + } + return data; + } } diff --git a/src/Chapter10/Listing10.16.ResourceCleanupWithIDisposable.cs b/src/Chapter10/Listing10.16.ResourceCleanupWithIDisposable.cs index 638944c14..6d809ab46 100644 --- a/src/Chapter10/Listing10.16.ResourceCleanupWithIDisposable.cs +++ b/src/Chapter10/Listing10.16.ResourceCleanupWithIDisposable.cs @@ -1,90 +1,89 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_16 -{ - #region INCLUDE - using System; - using System.IO; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_16; + +#region INCLUDE +using System; +using System.IO; - public static class Program +public static class Program +{ + // ... + public static void Search() { + TemporaryFileStream fileStream = + new(); + + // Use temporary file stream // ... - public static void Search() - { - TemporaryFileStream fileStream = - new(); - // Use temporary file stream - // ... + #region HIGHLIGHT + fileStream.Dispose(); + #endregion HIGHLIGHT - #region HIGHLIGHT - fileStream.Dispose(); - #endregion HIGHLIGHT + // ... + } +} - // ... - } +class TemporaryFileStream : IDisposable +{ + public TemporaryFileStream(string fileName) + { + File = new FileInfo(fileName); + Stream = new FileStream( + File.FullName, FileMode.OpenOrCreate, + FileAccess.ReadWrite); } - class TemporaryFileStream : IDisposable + public TemporaryFileStream() + : this(Path.GetTempFileName()) { } + + ~TemporaryFileStream() { - public TemporaryFileStream(string fileName) - { - File = new FileInfo(fileName); - Stream = new FileStream( - File.FullName, FileMode.OpenOrCreate, - FileAccess.ReadWrite); - } + #region HIGHLIGHT + Dispose(false); + #endregion HIGHLIGHT + } + + public FileStream? Stream { get; private set; } + public FileInfo? File { get; private set; } - public TemporaryFileStream() - : this(Path.GetTempFileName()) { } + #region IDisposable Members + #region HIGHLIGHT + public void Dispose() + { + Dispose(true); - ~TemporaryFileStream() + //unregister from the finalization queue. + System.GC.SuppressFinalize(this); + } + #endregion HIGHLIGHT + #endregion + #region HIGHLIGHT + public void Dispose(bool disposing) + { + // Do not dispose of an owned managed object (one with a + // finalizer) if called by member finalize, + // as the owned managed objects finalize method + // will be (or has been) called by finalization queue + // processing already + if (disposing) { - #region HIGHLIGHT - Dispose(false); - #endregion HIGHLIGHT + Stream?.Dispose(); } - - public FileStream? Stream { get; private set; } - public FileInfo? File { get; private set; } - - #region IDisposable Members + #endregion HIGHLIGHT + try #region HIGHLIGHT - public void Dispose() { - Dispose(true); - - //unregister from the finalization queue. - System.GC.SuppressFinalize(this); + File?.Delete(); } #endregion HIGHLIGHT - #endregion + catch (IOException exception) #region HIGHLIGHT - public void Dispose(bool disposing) { - // Do not dispose of an owned managed object (one with a - // finalizer) if called by member finalize, - // as the owned managed objects finalize method - // will be (or has been) called by finalization queue - // processing already - if (disposing) - { - Stream?.Dispose(); - } - #endregion HIGHLIGHT - try - #region HIGHLIGHT - { - File?.Delete(); - } - #endregion HIGHLIGHT - catch (IOException exception) - #region HIGHLIGHT - { - Console.WriteLine(exception); - } - #endregion HIGHLIGHT - Stream = null; - File = null; + Console.WriteLine(exception); } + #endregion HIGHLIGHT + Stream = null; + File = null; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter10/Listing10.17.InvokingTheUsingStatement.cs b/src/Chapter10/Listing10.17.InvokingTheUsingStatement.cs index 1458207e5..a5347790e 100644 --- a/src/Chapter10/Listing10.17.InvokingTheUsingStatement.cs +++ b/src/Chapter10/Listing10.17.InvokingTheUsingStatement.cs @@ -1,30 +1,29 @@ // Justification: Use to demonstrate pre-C# 8.0 syntax. #pragma warning disable IDE0063 // Use simple 'using' statement -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_17 -{ - using Listing10_16; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter10.Listing10_17; + +using Listing10_16; - #region INCLUDE - public static class Program +#region INCLUDE +public static class Program +{ + public static void Search() { - public static void Search() - { - #region HIGHLIGHT - // C# 8.0 - using TemporaryFileStream fileStream1 = new(); - #endregion HIGHLIGHT + #region HIGHLIGHT + // C# 8.0 + using TemporaryFileStream fileStream1 = new(); + #endregion HIGHLIGHT - #region HIGHLIGHT - // Prior to C# 8.0 - using (TemporaryFileStream fileStream2 = - new(), - fileStream3 = new()) - #endregion HIGHLIGHT - { - // Use temporary file stream; - } + #region HIGHLIGHT + // Prior to C# 8.0 + using (TemporaryFileStream fileStream2 = + new(), + fileStream3 = new()) + #endregion HIGHLIGHT + { + // Use temporary file stream; } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter11/Listing11.01.ThrowingAnException.cs b/src/Chapter11/Listing11.01.ThrowingAnException.cs index 3fd773a9f..3d8198e4d 100644 --- a/src/Chapter11/Listing11.01.ThrowingAnException.cs +++ b/src/Chapter11/Listing11.01.ThrowingAnException.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_01 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_01; + +using System; - #region INCLUDE - public sealed class TextNumberParser +#region INCLUDE +public sealed class TextNumberParser +{ + public static int Parse(string textDigit) { - public static int Parse(string textDigit) - { - string[] digitTexts = - { "zero", "one", "two", "three", "four", - "five", "six", "seven", "eight", "nine" }; + string[] digitTexts = + { "zero", "one", "two", "three", "four", + "five", "six", "seven", "eight", "nine" }; - int result = Array.IndexOf( - digitTexts, - // Leveraging C# 2.0’s null-coalescing operator - (textDigit ?? - // Leveraging C# 7.0’s throw expression - throw new ArgumentNullException(nameof(textDigit)) - ).ToLower()); + int result = Array.IndexOf( + digitTexts, + // Leveraging C# 2.0’s null-coalescing operator + (textDigit ?? + // Leveraging C# 7.0’s throw expression + throw new ArgumentNullException(nameof(textDigit)) + ).ToLower()); - if (result < 0) - { - // Leveraging C# 6.0's nameof operator - throw new ArgumentException( - "The argument did not represent a digit", nameof(textDigit)); - } - return result; + if (result < 0) + { + // Leveraging C# 6.0's nameof operator + throw new ArgumentException( + "The argument did not represent a digit", nameof(textDigit)); } + return result; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter11/Listing11.02.CatchingDifferentExceptionTypes.cs b/src/Chapter11/Listing11.02.CatchingDifferentExceptionTypes.cs index 756f9d955..5eaa7e7d5 100644 --- a/src/Chapter11/Listing11.02.CatchingDifferentExceptionTypes.cs +++ b/src/Chapter11/Listing11.02.CatchingDifferentExceptionTypes.cs @@ -1,55 +1,54 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_02 -{ +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_02; + #pragma warning disable 0168 // Disabled warning for unused variables for elucidation - using System.ComponentModel; - #region INCLUDE - using System; +using System.ComponentModel; +#region INCLUDE +using System; - public sealed class Program +public sealed class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) + try { - try - { - #region EXCLUDE - //throw new Win32Exception(42); - // ... - //TextNumberParser.Parse("negative forty-two"); - #endregion EXCLUDE - throw new InvalidOperationException( - "Arbitrary exception"); - // ... - } - catch(Win32Exception exception) - when(exception.NativeErrorCode == 42) - { - // Handle Win32Exception where - // ErrorCode is 42 - } - catch(ArgumentException exception) - { - // Handle ArgumentException - } - catch(InvalidOperationException exception) - { - bool exceptionHandled = false; - // Handle InvalidOperationException - // ... - if(!exceptionHandled) - { - throw; - } - } - catch(Exception exception) - { - // Handle Exception - } - finally + #region EXCLUDE + //throw new Win32Exception(42); + // ... + //TextNumberParser.Parse("negative forty-two"); + #endregion EXCLUDE + throw new InvalidOperationException( + "Arbitrary exception"); + // ... + } + catch(Win32Exception exception) + when(exception.NativeErrorCode == 42) + { + // Handle Win32Exception where + // ErrorCode is 42 + } + catch(ArgumentException exception) + { + // Handle ArgumentException + } + catch(InvalidOperationException exception) + { + bool exceptionHandled = false; + // Handle InvalidOperationException + // ... + if(!exceptionHandled) { - // Handle any cleanup code here as it runs - // regardless of whether there is an exception + throw; } } + catch(Exception exception) + { + // Handle Exception + } + finally + { + // Handle any cleanup code here as it runs + // regardless of whether there is an exception + } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter11/Listing11.03.UsingExceptionDispatchInfoToRethrowException.cs b/src/Chapter11/Listing11.03.UsingExceptionDispatchInfoToRethrowException.cs index 8956dbdbb..e0978a6fc 100644 --- a/src/Chapter11/Listing11.03.UsingExceptionDispatchInfoToRethrowException.cs +++ b/src/Chapter11/Listing11.03.UsingExceptionDispatchInfoToRethrowException.cs @@ -1,89 +1,88 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_03; + +#region INCLUDE +using System; +using System.Runtime.ExceptionServices; +using System.Threading.Tasks; +using System.Net; +using System.Linq; +using System.IO; +#region EXCLUDE +public sealed class Program { - #region INCLUDE - using System; - using System.Runtime.ExceptionServices; - using System.Threading.Tasks; - using System.Net; - using System.Linq; - using System.IO; - #region EXCLUDE - public sealed class Program + public static void Main(string[] args) { - public static void Main(string[] args) + string url = "http://www.IntelliTect.com"; + if (args.Length > 0) { - string url = "http://www.IntelliTect.com"; - if (args.Length > 0) - { - url = args[0]; - } + url = args[0]; + } - Console.Write(url); - #endregion EXCLUDE - Task task = WriteWebRequestSizeAsync(url); - try - { - while (!task.Wait(100)) - { - Console.Write("."); - } - } - catch (AggregateException exception) + Console.Write(url); +#endregion EXCLUDE + Task task = WriteWebRequestSizeAsync(url); + try + { + while (!task.Wait(100)) { - exception = exception.Flatten(); - #region HIGHLIGHT - ExceptionDispatchInfo.Capture( - exception.InnerException??exception).Throw(); - #endregion HIGHLIGHT + Console.Write("."); } - #endregion INCLUDE } - - - private static Task WriteWebRequestSizeAsync( - string url) + catch (AggregateException exception) { - StreamReader? reader = null; - WebRequest webRequest = - WebRequest.Create(url); + exception = exception.Flatten(); + #region HIGHLIGHT + ExceptionDispatchInfo.Capture( + exception.InnerException??exception).Throw(); + #endregion HIGHLIGHT + } +#endregion INCLUDE + } - Task task = - webRequest.GetResponseAsync() - .ContinueWith(antecedent => - { - WebResponse response = - antecedent.Result; - reader = - new StreamReader( - response.GetResponseStream()); - return reader.ReadToEndAsync(); - }) - .Unwrap() - .ContinueWith(antecedent => - { - if (reader != null) - reader.Dispose(); - string text = antecedent.Result; - Console.WriteLine( - FormatBytes(text.Length)); - }); + private static Task WriteWebRequestSizeAsync( + string url) + { + StreamReader? reader = null; + WebRequest webRequest = + WebRequest.Create(url); - return task; - } + Task task = + webRequest.GetResponseAsync() + .ContinueWith(antecedent => + { + WebResponse response = + antecedent.Result; - static public string FormatBytes(long bytes) + reader = + new StreamReader( + response.GetResponseStream()); + return reader.ReadToEndAsync(); + }) + .Unwrap() + .ContinueWith(antecedent => { - string[] magnitudes = - new string[] { "GB", "MB", "KB", "Bytes" }; - long max = - (long)Math.Pow(1024, magnitudes.Length); + if (reader != null) + reader.Dispose(); + string text = antecedent.Result; + Console.WriteLine( + FormatBytes(text.Length)); + }); - return string.Format("{1:##.##} {0}", - magnitudes.FirstOrDefault( - magnitude => - bytes > (max /= 1024)) ?? "0 Bytes", - (decimal)bytes / (decimal)max).Trim(); - } + return task; + } + + static public string FormatBytes(long bytes) + { + string[] magnitudes = + new string[] { "GB", "MB", "KB", "Bytes" }; + long max = + (long)Math.Pow(1024, magnitudes.Length); + + return string.Format("{1:##.##} {0}", + magnitudes.FirstOrDefault( + magnitude => + bytes > (max /= 1024)) ?? "0 Bytes", + (decimal)bytes / (decimal)max).Trim(); } } diff --git a/src/Chapter11/Listing11.06.OverflowingAnIntegerValue.cs b/src/Chapter11/Listing11.06.OverflowingAnIntegerValue.cs index ef2b6dde2..bc1d83bf9 100644 --- a/src/Chapter11/Listing11.06.OverflowingAnIntegerValue.cs +++ b/src/Chapter11/Listing11.06.OverflowingAnIntegerValue.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_06; + +#region INCLUDE +using System; +public class Program { - #region INCLUDE - using System; - public class Program + public static void Main() { - public static void Main() - { - // int.MaxValue equals 2147483647 - int n = int.MaxValue; - n = n + 1; - Console.WriteLine(n); - } + // int.MaxValue equals 2147483647 + int n = int.MaxValue; + n = n + 1; + Console.WriteLine(n); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter11/Listing11.07.ACheckedBlockExample.cs b/src/Chapter11/Listing11.07.ACheckedBlockExample.cs index 12c17bf10..2040de9fa 100644 --- a/src/Chapter11/Listing11.07.ACheckedBlockExample.cs +++ b/src/Chapter11/Listing11.07.ACheckedBlockExample.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_07; + +#region INCLUDE +using System; +public class Program { - #region INCLUDE - using System; - public class Program + public static void Main() { - public static void Main() + #region HIGHLIGHT + checked { - #region HIGHLIGHT - checked - { - #endregion HIGHLIGHT - // int.MaxValue equals 2147483647 - int n = int.MaxValue; - n = n + 1; - Console.WriteLine(n); - #region HIGHLIGHT - } - #endregion HIGHLIGHT + #endregion HIGHLIGHT + // int.MaxValue equals 2147483647 + int n = int.MaxValue; + n = n + 1; + Console.WriteLine(n); + #region HIGHLIGHT } + #endregion HIGHLIGHT } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter11/Listing11.08.AnUnCheckedBlockExample.cs b/src/Chapter11/Listing11.08.AnUnCheckedBlockExample.cs index 705d64bb7..9c93c09a4 100644 --- a/src/Chapter11/Listing11.08.AnUnCheckedBlockExample.cs +++ b/src/Chapter11/Listing11.08.AnUnCheckedBlockExample.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter11.Listing11_08; + +#region INCLUDE +using System; +public class Program { - #region INCLUDE - using System; - public class Program + public static void Main() { - public static void Main() + #region HIGHLIGHT + unchecked { - #region HIGHLIGHT - unchecked - { - #endregion HIGHLIGHT - // int.MaxValue equals 2147483647 - int n = int.MaxValue; - n = n + 1; - Console.WriteLine(n); - #region HIGHLIGHT - } - #endregion HIGHLIGHT + #endregion HIGHLIGHT + // int.MaxValue equals 2147483647 + int n = int.MaxValue; + n = n + 1; + Console.WriteLine(n); + #region HIGHLIGHT } + #endregion HIGHLIGHT } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Contact.cs b/src/Chapter12/Contact.cs index 7375d41a0..1400bd98f 100644 --- a/src/Chapter12/Contact.cs +++ b/src/Chapter12/Contact.cs @@ -1,71 +1,69 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12 -{ - using Chapter08.Listing08_02; - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12; - interface IPerson - { - string FirstName - { - get; - set; - } +using Chapter08.Listing08_02; +using System; - string LastName - { - get; - set; - } +interface IPerson +{ + string FirstName + { + get; + set; } - public class Person : IPerson + string LastName { - public Person(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } - public string? _FirstName; - public string FirstName - { - get => _FirstName!; - set => _FirstName = value ?? throw new ArgumentNullException(nameof(value)); - } - public string? _LastName; - public string LastName - { - get => _LastName!; - set => _LastName = value ?? throw new ArgumentNullException(nameof(value)); - } + get; + set; } +} - public class Contact : PdaItem, IPerson +public class Person : IPerson +{ + public Person(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + } + public string? _FirstName; + public string FirstName + { + get => _FirstName!; + set => _FirstName = value ?? throw new ArgumentNullException(nameof(value)); + } + public string? _LastName; + public string LastName { - public Contact(string name) - : base(name) - { - } + get => _LastName!; + set => _LastName = value ?? throw new ArgumentNullException(nameof(value)); + } +} - private Person Person - { - get { return _Person!; } - set { _Person = value ?? throw new ArgumentNullException(nameof(value)); } - } - private Person? _Person; +public class Contact : PdaItem, IPerson +{ + public Contact(string name) + : base(name) + { + } - public string FirstName - { - get { return Person.FirstName; } - set { Person.FirstName = value; } - } + private Person Person + { + get { return _Person!; } + set { _Person = value ?? throw new ArgumentNullException(nameof(value)); } + } + private Person? _Person; - public string LastName - { - get { return Person.LastName; } - set { Person.LastName = value; } - } + public string FirstName + { + get { return Person.FirstName; } + set { Person.FirstName = value; } + } - // ... + public string LastName + { + get { return Person.LastName; } + set { Person.LastName = value; } } + // ... } diff --git a/src/Chapter12/INullable.cs b/src/Chapter12/INullable.cs index b7c7336f8..eca40ade1 100644 --- a/src/Chapter12/INullable.cs +++ b/src/Chapter12/INullable.cs @@ -1,7 +1,6 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_24 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_24; + +public interface INullable { - public interface INullable - { - bool IsNull { get; } - } + bool IsNull { get; } } diff --git a/src/Chapter12/Listing12.01.TheSystemCollectionsStackMethodSignatures.cs b/src/Chapter12/Listing12.01.TheSystemCollectionsStackMethodSignatures.cs index d2db4ee94..03237a617 100644 --- a/src/Chapter12/Listing12.01.TheSystemCollectionsStackMethodSignatures.cs +++ b/src/Chapter12/Listing12.01.TheSystemCollectionsStackMethodSignatures.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_01; + +#region INCLUDE +public class Stack { - #region INCLUDE - public class Stack + public virtual object Pop() { - public virtual object Pop() - { - #region EXCLUDE - return new object(); - #endregion EXCLUDE - } + #region EXCLUDE + return new object(); + #endregion EXCLUDE + } - public virtual void Push(object obj) - { - // ... - } + public virtual void Push(object obj) + { // ... } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.02.SupportingUndoInEtchASketchGame.cs b/src/Chapter12/Listing12.02.SupportingUndoInEtchASketchGame.cs index 9782244ef..b861a9c86 100644 --- a/src/Chapter12/Listing12.02.SupportingUndoInEtchASketchGame.cs +++ b/src/Chapter12/Listing12.02.SupportingUndoInEtchASketchGame.cs @@ -1,150 +1,149 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_02; + +using System; +#region INCLUDE +using System.Collections.Generic; + +public class Program { - using System; - #region INCLUDE - using System.Collections.Generic; + #region EXCLUDE + public static void Main() + { + Sketch(); + } + #endregion EXCLUDE - public class Program + public static void Sketch() { + Stack path = new Stack(); + Cell currentPosition; + ConsoleKeyInfo key; #region EXCLUDE - public static void Main() + Console.WriteLine("Use arrow keys to draw. X to exit."); + for(int i = 2; i < Console.WindowHeight; i++) { - Sketch(); + Console.WriteLine(); } + + currentPosition = new Cell(Console.WindowWidth / 2, Console.WindowHeight / 2); + path.Push(currentPosition); + FillCell(currentPosition); #endregion EXCLUDE - public static void Sketch() + do { - Stack path = new Stack(); - Cell currentPosition; - ConsoleKeyInfo key; - #region EXCLUDE - Console.WriteLine("Use arrow keys to draw. X to exit."); - for(int i = 2; i < Console.WindowHeight; i++) - { - Console.WriteLine(); - } - - currentPosition = new Cell(Console.WindowWidth / 2, Console.WindowHeight / 2); - path.Push(currentPosition); - FillCell(currentPosition); - #endregion EXCLUDE + // Etch in the direction indicated by the + // arrow keys that the user enters + key = Move(); - do + switch(key.Key) { - // Etch in the direction indicated by the - // arrow keys that the user enters - key = Move(); - - switch(key.Key) - { - case ConsoleKey.Z: - // Undo the previous Move - if(path.Count >= 1) - { - #region HIGHLIGHT - currentPosition = (Cell)path.Pop(); - #endregion HIGHLIGHT - Console.SetCursorPosition( - currentPosition.X, currentPosition.Y); - #region EXCLUDE - FillCell(currentPosition, ConsoleColor.Black); - #endregion EXCLUDE - Undo(); - } - break; - case ConsoleKey.DownArrow: - #region EXCLUDE - if (Console.CursorTop < Console.WindowHeight - 2) - { - currentPosition = new Cell( - Console.CursorLeft, Console.CursorTop + 1); - } - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.UpArrow: - #region EXCLUDE - if (Console.CursorTop > 1) - { - currentPosition = new Cell( - Console.CursorLeft, Console.CursorTop - 1); - } - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.LeftArrow: - #region EXCLUDE - if (Console.CursorLeft > 1) - { - currentPosition = new Cell( - Console.CursorLeft - 1, Console.CursorTop); - } - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.RightArrow: - // SaveState() - if(Console.CursorLeft < Console.WindowWidth - 2) - { - currentPosition = new Cell( - Console.CursorLeft + 1, Console.CursorTop); - } + case ConsoleKey.Z: + // Undo the previous Move + if(path.Count >= 1) + { #region HIGHLIGHT - path.Push(currentPosition); + currentPosition = (Cell)path.Pop(); #endregion HIGHLIGHT + Console.SetCursorPosition( + currentPosition.X, currentPosition.Y); #region EXCLUDE - FillCell(currentPosition); + FillCell(currentPosition, ConsoleColor.Black); #endregion EXCLUDE - break; + Undo(); + } + break; + case ConsoleKey.DownArrow: + #region EXCLUDE + if (Console.CursorTop < Console.WindowHeight - 2) + { + currentPosition = new Cell( + Console.CursorLeft, Console.CursorTop + 1); + } + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.UpArrow: + #region EXCLUDE + if (Console.CursorTop > 1) + { + currentPosition = new Cell( + Console.CursorLeft, Console.CursorTop - 1); + } + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.LeftArrow: + #region EXCLUDE + if (Console.CursorLeft > 1) + { + currentPosition = new Cell( + Console.CursorLeft - 1, Console.CursorTop); + } + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.RightArrow: + // SaveState() + if(Console.CursorLeft < Console.WindowWidth - 2) + { + currentPosition = new Cell( + Console.CursorLeft + 1, Console.CursorTop); + } + #region HIGHLIGHT + path.Push(currentPosition); + #endregion HIGHLIGHT + #region EXCLUDE + FillCell(currentPosition); + #endregion EXCLUDE + break; - default: - Console.Beep(); - break; - } + default: + Console.Beep(); + break; } - while(key.Key != ConsoleKey.X); // Use X to quit. - } - #region EXCLUDE - private static ConsoleKeyInfo Move() - { - return Console.ReadKey(true); - } - - private static void Undo() - { - // stub } + while(key.Key != ConsoleKey.X); // Use X to quit. + } + #region EXCLUDE + private static ConsoleKeyInfo Move() + { + return Console.ReadKey(true); + } - private static void FillCell(Cell cell) - { - FillCell(cell, ConsoleColor.White); - } + private static void Undo() + { + // stub + } - private static void FillCell(Cell cell, ConsoleColor color) - { - Console.SetCursorPosition(cell.X, cell.Y); - Console.BackgroundColor = color; - Console.Write(' '); - Console.SetCursorPosition(cell.X, cell.Y); - Console.BackgroundColor = ConsoleColor.Black; - } - #endregion EXCLUDE + private static void FillCell(Cell cell) + { + FillCell(cell, ConsoleColor.White); } - public struct Cell + private static void FillCell(Cell cell, ConsoleColor color) { - public int X { get; } - public int Y { get; } + Console.SetCursorPosition(cell.X, cell.Y); + Console.BackgroundColor = color; + Console.Write(' '); + Console.SetCursorPosition(cell.X, cell.Y); + Console.BackgroundColor = ConsoleColor.Black; + } + #endregion EXCLUDE +} - public Cell(int x, int y) - { - X = x; - Y = y; - } +public struct Cell +{ + public int X { get; } + public int Y { get; } + + public Cell(int x, int y) + { + X = x; + Y = y; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.03.DefiningASpecializedStackClass.cs b/src/Chapter12/Listing12.03.DefiningASpecializedStackClass.cs index 001b7e086..ef4e1d0d1 100644 --- a/src/Chapter12/Listing12.03.DefiningASpecializedStackClass.cs +++ b/src/Chapter12/Listing12.03.DefiningASpecializedStackClass.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_03; + +using Listing12_02; +#region INCLUDE +public class CellStack { - using Listing12_02; - #region INCLUDE - public class CellStack - { - public virtual Cell Pop() { return new Cell(); } // would return that last cell added and remove it from the list - public virtual void Push(Cell cell) { } - // ... - } - #endregion INCLUDE + public virtual Cell Pop() { return new Cell(); } // would return that last cell added and remove it from the list + public virtual void Push(Cell cell) { } + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.04.DeclaringVersionsOfVariousValueTypesThatStoreNull.cs b/src/Chapter12/Listing12.04.DeclaringVersionsOfVariousValueTypesThatStoreNull.cs index 270ecc25d..cc4987eac 100644 --- a/src/Chapter12/Listing12.04.DeclaringVersionsOfVariousValueTypesThatStoreNull.cs +++ b/src/Chapter12/Listing12.04.DeclaringVersionsOfVariousValueTypesThatStoreNull.cs @@ -1,40 +1,39 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_04; + +using System; + +#region INCLUDE +struct NullableInt +{ + /// + /// Provides the value when HasValue returns true + /// + public int Value { get; private set; } + + /// + /// Indicates whether there is a value or whether + /// the value is "null" + /// + public bool HasValue { get; private set; } + + // ... +} + +struct NullableGuid { - using System; - - #region INCLUDE - struct NullableInt - { - /// - /// Provides the value when HasValue returns true - /// - public int Value { get; private set; } - - /// - /// Indicates whether there is a value or whether - /// the value is "null" - /// - public bool HasValue { get; private set; } - - // ... - } - - struct NullableGuid - { - /// - /// Provides the value when HasValue returns true - /// - public Guid Value { get; private set; } - - /// - /// Indicates whether there is a value or whether - /// the value is "null" - /// - public bool HasValue { get; private set; } - - // ... - } + /// + /// Provides the value when HasValue returns true + /// + public Guid Value { get; private set; } + + /// + /// Indicates whether there is a value or whether + /// the value is "null" + /// + public bool HasValue { get; private set; } // ... - #endregion INCLUDE } + +// ... +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.05.DeclaringANullableTypeThatContainsAValuePropertyOfTypeObject.cs b/src/Chapter12/Listing12.05.DeclaringANullableTypeThatContainsAValuePropertyOfTypeObject.cs index 6a1993ec7..4c3f7bdc6 100644 --- a/src/Chapter12/Listing12.05.DeclaringANullableTypeThatContainsAValuePropertyOfTypeObject.cs +++ b/src/Chapter12/Listing12.05.DeclaringANullableTypeThatContainsAValuePropertyOfTypeObject.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_05; + +#region INCLUDE +struct Nullable { - #region INCLUDE - struct Nullable - { - /// - /// Provides the value when HasValue returns true. - /// - public object Value { get; private set; } + /// + /// Provides the value when HasValue returns true. + /// + public object Value { get; private set; } - /// - /// Indicates whether there is a value or whether - /// the value is "null" - /// - public bool HasValue { get; private set; } + /// + /// Indicates whether there is a value or whether + /// the value is "null" + /// + public bool HasValue { get; private set; } - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.06.ImplementingUndoWithAGenericStackClass.cs b/src/Chapter12/Listing12.06.ImplementingUndoWithAGenericStackClass.cs index 5943f7b2b..9b95e6ffe 100644 --- a/src/Chapter12/Listing12.06.ImplementingUndoWithAGenericStackClass.cs +++ b/src/Chapter12/Listing12.06.ImplementingUndoWithAGenericStackClass.cs @@ -1,153 +1,152 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_06; + +#region INCLUDE +using System; +using System.Collections.Generic; + +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; + #region EXCLUDE + public static void Main() + { + Sketch(); + } + #endregion EXCLUDE - public class Program + public static void Sketch() { + #region HIGHLIGHT + Stack path = new Stack(); + #endregion HIGHLIGHT + Cell currentPosition; + ConsoleKeyInfo key; #region EXCLUDE - public static void Main() + Console.WriteLine("Use arrow keys to draw. X to exit."); + for(int i = 2; i < Console.WindowHeight; i++) { - Sketch(); + Console.WriteLine(); } + + currentPosition = new Cell(Console.WindowWidth / 2, Console.WindowHeight / 2); + path.Push(currentPosition); + FillCell(currentPosition); #endregion EXCLUDE - public static void Sketch() + do { - #region HIGHLIGHT - Stack path = new Stack(); - #endregion HIGHLIGHT - Cell currentPosition; - ConsoleKeyInfo key; - #region EXCLUDE - Console.WriteLine("Use arrow keys to draw. X to exit."); - for(int i = 2; i < Console.WindowHeight; i++) - { - Console.WriteLine(); - } + // Etch in the direction indicated by the + // arrow keys that the user enters + key = Move(); - currentPosition = new Cell(Console.WindowWidth / 2, Console.WindowHeight / 2); - path.Push(currentPosition); - FillCell(currentPosition); - #endregion EXCLUDE - - do + switch(key.Key) { - // Etch in the direction indicated by the - // arrow keys that the user enters - key = Move(); - - switch(key.Key) - { - case ConsoleKey.Z: - // Undo the previous Move - if(path.Count >= 1) - { - #region HIGHLIGHT - // No cast required - currentPosition = path.Pop(); - #endregion HIGHLIGHT - Console.SetCursorPosition( - currentPosition.X, currentPosition.Y); - FillCell(currentPosition, ConsoleColor.Black); - Undo(); - } - break; - case ConsoleKey.DownArrow: - #region EXCLUDE - if (Console.CursorTop < Console.WindowHeight - 2) - { - currentPosition = new Cell( - Console.CursorLeft, Console.CursorTop + 1); - } - // Only type Cell allowed in call to Push() - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.UpArrow: - #region EXCLUDE - if (Console.CursorTop > 1) - { - currentPosition = new Cell( - Console.CursorLeft, Console.CursorTop - 1); - } - // Only type Cell allowed in call to Push() - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.LeftArrow: - #region EXCLUDE - if (Console.CursorLeft > 1) - { - currentPosition = new Cell( - Console.CursorLeft - 1, Console.CursorTop); - } - // Only type Cell allowed in call to Push() - path.Push(currentPosition); - FillCell(currentPosition); - break; - #endregion EXCLUDE - case ConsoleKey.RightArrow: - // SaveState() - if(Console.CursorLeft < Console.WindowWidth - 2) - { - currentPosition = new Cell( - Console.CursorLeft + 1, Console.CursorTop); - } + case ConsoleKey.Z: + // Undo the previous Move + if(path.Count >= 1) + { #region HIGHLIGHT - // Only type Cell allowed in call to Push() - path.Push(currentPosition); + // No cast required + currentPosition = path.Pop(); #endregion HIGHLIGHT - FillCell(currentPosition); - break; - - default: - Console.Beep(); - break; - } + Console.SetCursorPosition( + currentPosition.X, currentPosition.Y); + FillCell(currentPosition, ConsoleColor.Black); + Undo(); + } + break; + case ConsoleKey.DownArrow: + #region EXCLUDE + if (Console.CursorTop < Console.WindowHeight - 2) + { + currentPosition = new Cell( + Console.CursorLeft, Console.CursorTop + 1); + } + // Only type Cell allowed in call to Push() + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.UpArrow: + #region EXCLUDE + if (Console.CursorTop > 1) + { + currentPosition = new Cell( + Console.CursorLeft, Console.CursorTop - 1); + } + // Only type Cell allowed in call to Push() + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.LeftArrow: + #region EXCLUDE + if (Console.CursorLeft > 1) + { + currentPosition = new Cell( + Console.CursorLeft - 1, Console.CursorTop); + } + // Only type Cell allowed in call to Push() + path.Push(currentPosition); + FillCell(currentPosition); + break; + #endregion EXCLUDE + case ConsoleKey.RightArrow: + // SaveState() + if(Console.CursorLeft < Console.WindowWidth - 2) + { + currentPosition = new Cell( + Console.CursorLeft + 1, Console.CursorTop); + } + #region HIGHLIGHT + // Only type Cell allowed in call to Push() + path.Push(currentPosition); + #endregion HIGHLIGHT + FillCell(currentPosition); + break; + default: + Console.Beep(); + break; } - while(key.Key != ConsoleKey.X); // Use X to quit - } - #region EXCLUDE - private static ConsoleKeyInfo Move() - { - return Console.ReadKey(true); - } - private static void Undo() - { - // stub } + while(key.Key != ConsoleKey.X); // Use X to quit + } + #region EXCLUDE + private static ConsoleKeyInfo Move() + { + return Console.ReadKey(true); + } - private static void FillCell(Cell cell) - { - FillCell(cell, ConsoleColor.White); - } + private static void Undo() + { + // stub + } - private static void FillCell(Cell cell, ConsoleColor color) - { - Console.SetCursorPosition(cell.X, cell.Y); - Console.BackgroundColor = color; - Console.Write(' '); - Console.SetCursorPosition(cell.X, cell.Y); - Console.BackgroundColor = ConsoleColor.Black; - } - #endregion EXCLUDE + private static void FillCell(Cell cell) + { + FillCell(cell, ConsoleColor.White); } - #endregion INCLUDE - public struct Cell + + private static void FillCell(Cell cell, ConsoleColor color) { - readonly public int X; - readonly public int Y; + Console.SetCursorPosition(cell.X, cell.Y); + Console.BackgroundColor = color; + Console.Write(' '); + Console.SetCursorPosition(cell.X, cell.Y); + Console.BackgroundColor = ConsoleColor.Black; + } + #endregion EXCLUDE +} +#endregion INCLUDE +public struct Cell +{ + readonly public int X; + readonly public int Y; - public Cell(int x, int y) - { - X = x; - Y = y; - } + public Cell(int x, int y) + { + X = x; + Y = y; } } diff --git a/src/Chapter12/Listing12.07.DeclaringAGenericClassStack.cs b/src/Chapter12/Listing12.07.DeclaringAGenericClassStack.cs index bba33cf48..a955f0b8e 100644 --- a/src/Chapter12/Listing12.07.DeclaringAGenericClassStack.cs +++ b/src/Chapter12/Listing12.07.DeclaringAGenericClassStack.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_07; + +#region INCLUDE +public class Stack { - #region INCLUDE - public class Stack + public Stack(int maxSize) { - public Stack(int maxSize) - { - InternalItems = new T[maxSize]; - } + InternalItems = new T[maxSize]; + } - private T[] InternalItems { get; } + private T[] InternalItems { get; } - public void Push(T data) - { - //... - } + public void Push(T data) + { + //... + } - public T Pop() - { - #region EXCLUDE - return InternalItems[0]; //just for the example - #endregion EXCLUDE - } + public T Pop() + { + #region EXCLUDE + return InternalItems[0]; //just for the example + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.08.DeclaringAGenericInterface.cs b/src/Chapter12/Listing12.08.DeclaringAGenericInterface.cs index 9788e51c6..0317b25d7 100644 --- a/src/Chapter12/Listing12.08.DeclaringAGenericInterface.cs +++ b/src/Chapter12/Listing12.08.DeclaringAGenericInterface.cs @@ -1,10 +1,9 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_08; + +#region INCLUDE +interface IPair { - #region INCLUDE - interface IPair - { - T First { get; set; } - T Second { get; set; } - } - #endregion INCLUDE + T First { get; set; } + T Second { get; set; } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.09.ImplementingAGenericInterface.cs b/src/Chapter12/Listing12.09.ImplementingAGenericInterface.cs index 10fc6124c..3dd2dd349 100644 --- a/src/Chapter12/Listing12.09.ImplementingAGenericInterface.cs +++ b/src/Chapter12/Listing12.09.ImplementingAGenericInterface.cs @@ -1,11 +1,10 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_09; + +using Listing12_08; +#region INCLUDE +public struct Pair : IPair { - using Listing12_08; - #region INCLUDE - public struct Pair : IPair - { - public T First { get; set; } - public T Second { get; set; } - } - #endregion INCLUDE + public T First { get; set; } + public T Second { get; set; } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.10.DuplicatingAnInterfaceImplementationOnASingleClass.cs b/src/Chapter12/Listing12.10.DuplicatingAnInterfaceImplementationOnASingleClass.cs index 46d1da245..03fd734f4 100644 --- a/src/Chapter12/Listing12.10.DuplicatingAnInterfaceImplementationOnASingleClass.cs +++ b/src/Chapter12/Listing12.10.DuplicatingAnInterfaceImplementationOnASingleClass.cs @@ -1,64 +1,63 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_10; + +using System.Collections.Generic; +#region INCLUDE +public interface IContainer +{ + ICollection Items { get; set; } +} + +public class Person : IContainer
, + IContainer, IContainer { - using System.Collections.Generic; - #region INCLUDE - public interface IContainer + #region HIGHLIGHT + ICollection
IContainer
.Items + #endregion HIGHLIGHT { - ICollection Items { get; set; } + get + { + #region EXCLUDE + return new List
(); + #endregion EXCLUDE + } + set + { + //... + } } - - public class Person : IContainer
, - IContainer, IContainer + #region HIGHLIGHT + ICollection IContainer.Items + #endregion HIGHLIGHT { - #region HIGHLIGHT - ICollection
IContainer
.Items - #endregion HIGHLIGHT + get { - get - { - #region EXCLUDE - return new List
(); - #endregion EXCLUDE - } - set - { - //... - } + #region EXCLUDE + return new List(); + #endregion EXCLUDE } - #region HIGHLIGHT - ICollection IContainer.Items - #endregion HIGHLIGHT + set { - get - { - #region EXCLUDE - return new List(); - #endregion EXCLUDE - } - set - { - //... - } + //... } - #region HIGHLIGHT - ICollection IContainer.Items - #endregion HIGHLIGHT + } + #region HIGHLIGHT + ICollection IContainer.Items + #endregion HIGHLIGHT + { + get { - get - { - #region EXCLUDE - return new List(); - #endregion EXCLUDE - } - set - { - //... - } + #region EXCLUDE + return new List(); + #endregion EXCLUDE + } + set + { + //... } } - #endregion INCLUDE - - public class Address { } // For example purposes only - public class Phone { } // For example purposes only - public class Email { } // For example purposes only } +#endregion INCLUDE + +public class Address { } // For example purposes only +public class Phone { } // For example purposes only +public class Email { } // For example purposes only diff --git a/src/Chapter12/Listing12.11.DeclaringAGenericTypeConstructor.cs b/src/Chapter12/Listing12.11.DeclaringAGenericTypeConstructor.cs index 5e6a3418e..9ee94e3fd 100644 --- a/src/Chapter12/Listing12.11.DeclaringAGenericTypeConstructor.cs +++ b/src/Chapter12/Listing12.11.DeclaringAGenericTypeConstructor.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_11; + +using Listing12_08; +#region INCLUDE +public struct Pair : IPair { - using Listing12_08; - #region INCLUDE - public struct Pair : IPair + #region HIGHLIGHT + public Pair(T first, T second) { - #region HIGHLIGHT - public Pair(T first, T second) - { - First = first; - Second = second; - } - #endregion HIGHLIGHT - - public T First { get; set; } - public T Second { get; set; } + First = first; + Second = second; } - #endregion INCLUDE + #endregion HIGHLIGHT + + public T First { get; set; } + public T Second { get; set; } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.12.NotInitializingAllFieldsCasuingACompileError.cs b/src/Chapter12/Listing12.12.NotInitializingAllFieldsCasuingACompileError.cs index 377bc78c4..9ceb09a6a 100644 --- a/src/Chapter12/Listing12.12.NotInitializingAllFieldsCasuingACompileError.cs +++ b/src/Chapter12/Listing12.12.NotInitializingAllFieldsCasuingACompileError.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_12 -{ - using Listing12_08; - #region INCLUDE - public struct Pair : IPair - { - // ERROR: Field 'Pair.Second' must be fully assigned - // before control leaves the constructor - // public Pair(T first) - // { - // First = first; - // } +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_12; - #region EXCLUDE - public Pair(T first, T second) - { - First = first; - Second = second; - } +using Listing12_08; +#region INCLUDE +public struct Pair : IPair +{ + // ERROR: Field 'Pair.Second' must be fully assigned + // before control leaves the constructor + // public Pair(T first) + // { + // First = first; + // } - public T First { get; set; } - public T Second { get; set; } - #endregion EXCLUDE + #region EXCLUDE + public Pair(T first, T second) + { + First = first; + Second = second; } - #endregion INCLUDE + + public T First { get; set; } + public T Second { get; set; } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.13.InitializingAFieldWithTheDefaultOperator.cs b/src/Chapter12/Listing12.13.InitializingAFieldWithTheDefaultOperator.cs index 9a8ae4715..c3cff171a 100644 --- a/src/Chapter12/Listing12.13.InitializingAFieldWithTheDefaultOperator.cs +++ b/src/Chapter12/Listing12.13.InitializingAFieldWithTheDefaultOperator.cs @@ -1,37 +1,36 @@ // Justification: Only showing partial implementaiton. #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_13; + +using Listing12_08; +#region INCLUDE +public struct Pair : IPair { - using Listing12_08; - #region INCLUDE - public struct Pair : IPair + public Pair(T first) { - public Pair(T first) - { - First = first; - #region EXCLUDE - // Justifiction: Ignore warning pending struct/class constraints, later on in the chapter, - // so that Second can be declared as T?. - #pragma warning disable CS8601 // Possible null reference assignment. - #endregion EXCLUDE - #region HIGHLIGHT - Second = default; - #endregion HIGHLIGHT - #region EXCLUDE - #pragma warning restore CS8601 // Possible null reference assignment. - #endregion EXCLUDE - } + First = first; #region EXCLUDE - public Pair(T first, T second) - { - First = first; - Second = second; - } - - public T First { get; set; } - public T Second { get; set; } + // Justifiction: Ignore warning pending struct/class constraints, later on in the chapter, + // so that Second can be declared as T?. +#pragma warning disable CS8601 // Possible null reference assignment. + #endregion EXCLUDE + #region HIGHLIGHT + Second = default; + #endregion HIGHLIGHT + #region EXCLUDE +#pragma warning restore CS8601 // Possible null reference assignment. #endregion EXCLUDE } - #endregion INCLUDE + #region EXCLUDE + public Pair(T first, T second) + { + First = first; + Second = second; + } + + public T First { get; set; } + public T Second { get; set; } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.14.DeclaringAGenericWithMultipleTypeParameters.cs b/src/Chapter12/Listing12.14.DeclaringAGenericWithMultipleTypeParameters.cs index a4588a362..e17bb5e8b 100644 --- a/src/Chapter12/Listing12.14.DeclaringAGenericWithMultipleTypeParameters.cs +++ b/src/Chapter12/Listing12.14.DeclaringAGenericWithMultipleTypeParameters.cs @@ -1,22 +1,21 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_14; + +#region INCLUDE +interface IPair { - #region INCLUDE - interface IPair - { - TFirst First { get; set; } - TSecond Second { get; set; } - } + TFirst First { get; set; } + TSecond Second { get; set; } +} - public struct Pair : IPair +public struct Pair : IPair +{ + public Pair(TFirst first, TSecond second) { - public Pair(TFirst first, TSecond second) - { - First = first; - Second = second; - } - - public TFirst First { get; set; } - public TSecond Second { get; set; } + First = first; + Second = second; } - #endregion INCLUDE + + public TFirst First { get; set; } + public TSecond Second { get; set; } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.15.UsingATypewithMultipleTypeParameters.cs b/src/Chapter12/Listing12.15.UsingATypewithMultipleTypeParameters.cs index 81addde66..49abe3d06 100644 --- a/src/Chapter12/Listing12.15.UsingATypewithMultipleTypeParameters.cs +++ b/src/Chapter12/Listing12.15.UsingATypewithMultipleTypeParameters.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_15 -{ - using System; - using Listing12_14; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_15; + +using System; +using Listing12_14; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - Pair historicalEvent = - new Pair(1914, - "Shackleton leaves for South Pole on ship Endurance"); + #region INCLUDE + Pair historicalEvent = + new Pair(1914, + "Shackleton leaves for South Pole on ship Endurance"); - Console.WriteLine("{0}: {1}", - historicalEvent.First, historicalEvent.Second); - #endregion INCLUDE - } + Console.WriteLine("{0}: {1}", + historicalEvent.First, historicalEvent.Second); + #endregion INCLUDE } } diff --git a/src/Chapter12/Listing12.16.UsingArityToOverloadATypeDefinition.cs b/src/Chapter12/Listing12.16.UsingArityToOverloadATypeDefinition.cs index 31025ee53..a22fda9b4 100644 --- a/src/Chapter12/Listing12.16.UsingArityToOverloadATypeDefinition.cs +++ b/src/Chapter12/Listing12.16.UsingArityToOverloadATypeDefinition.cs @@ -1,41 +1,40 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_16 -{ - #region INCLUDE - public class Tuple - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable - { - // ... - } - #endregion INCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_16; + +#region INCLUDE +public class Tuple +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... +} +public class Tuple // : IStructuralEquatable, IStructuralComparable, IComparable +{ + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.17.ComparingSystemValueTupleInstantiationApproaches.cs b/src/Chapter12/Listing12.17.ComparingSystemValueTupleInstantiationApproaches.cs index a6a4c0804..730c8c663 100644 --- a/src/Chapter12/Listing12.17.ComparingSystemValueTupleInstantiationApproaches.cs +++ b/src/Chapter12/Listing12.17.ComparingSystemValueTupleInstantiationApproaches.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_17 -{ +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_17; + #pragma warning disable 0219 // Disabled warning for assigned but never - // used variables for elucidation - using Contact = Chapter12.Contact; +// used variables for elucidation +using Contact = Chapter12.Contact; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - #if !PRECSHARP7 - (string, Contact) keyValuePair; - keyValuePair = - ("555-55-5555", new Contact("Inigo Montoya")); - #else // Use System.ValueTupe prior to C# 7.0 - ValueTuple keyValuePair; - keyValuePair = - #region HIGHLIGHT - ValueTuple.Create( - #endregion HIGHLIGHT - "555-55-5555", new Contact("Inigo Montoya")); - keyValuePair = - #region HIGHLIGHT - new ValueTuple( - #endregion HIGHLIGHT - "555-55-5555", new Contact("Inigo Montoya")); - #endif // !PRECSHARP7 - #endregion INCLUDE - } + #region INCLUDE + #if !PRECSHARP7 + (string, Contact) keyValuePair; + keyValuePair = + ("555-55-5555", new Contact("Inigo Montoya")); + #else // Use System.ValueTupe prior to C# 7.0 + ValueTuple keyValuePair; + keyValuePair = + #region HIGHLIGHT + ValueTuple.Create( + #endregion HIGHLIGHT + "555-55-5555", new Contact("Inigo Montoya")); + keyValuePair = + #region HIGHLIGHT + new ValueTuple( + #endregion HIGHLIGHT + "555-55-5555", new Contact("Inigo Montoya")); + #endif // !PRECSHARP7 + #endregion INCLUDE } } diff --git a/src/Chapter12/Listing12.18.NestedGenericTypes.cs b/src/Chapter12/Listing12.18.NestedGenericTypes.cs index 44254d777..88385ce49 100644 --- a/src/Chapter12/Listing12.18.NestedGenericTypes.cs +++ b/src/Chapter12/Listing12.18.NestedGenericTypes.cs @@ -1,21 +1,20 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_18; + +#pragma warning disable 0693 // Disabled warning due to nested type parameter +// with overlapping name +#region INCLUDE +public class Container { - #pragma warning disable 0693 // Disabled warning due to nested type parameter - // with overlapping name - #region INCLUDE - public class Container + // Nested classes inherit type parameter + // Reusing a type parameter name will cause + // a warning + public class Nested { - // Nested classes inherit type parameter - // Reusing a type parameter name will cause - // a warning - public class Nested + #region HIGHLIGHT + static void Method(T param0, U param1) + #endregion HIGHLIGHT { - #region HIGHLIGHT - static void Method(T param0, U param1) - #endregion HIGHLIGHT - { - } } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.19.DeclaringABinaryTreeClassWithNoConstraints.cs b/src/Chapter12/Listing12.19.DeclaringABinaryTreeClassWithNoConstraints.cs index 66c2f7307..46bd52339 100644 --- a/src/Chapter12/Listing12.19.DeclaringABinaryTreeClassWithNoConstraints.cs +++ b/src/Chapter12/Listing12.19.DeclaringABinaryTreeClassWithNoConstraints.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_19; + +using Listing12_13; +#region INCLUDE +public class BinaryTree { - using Listing12_13; - #region INCLUDE - public class BinaryTree + public BinaryTree(T item) { - public BinaryTree(T item) - { - Item = item; - } - - public T Item { get; set; } - public Pair> SubItems { get; set; } + Item = item; } - #endregion INCLUDE + + public T Item { get; set; } + public Pair> SubItems { get; set; } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.20.NeedingTheTypeParameterToSupportAnInterface.cs b/src/Chapter12/Listing12.20.NeedingTheTypeParameterToSupportAnInterface.cs index 9735d9b28..e2407abb5 100644 --- a/src/Chapter12/Listing12.20.NeedingTheTypeParameterToSupportAnInterface.cs +++ b/src/Chapter12/Listing12.20.NeedingTheTypeParameterToSupportAnInterface.cs @@ -1,45 +1,45 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_20 -{ - using System; - using Listing12_13; - // In an actual implementation Item would be used to hold some value +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_20; + +using System; +using Listing12_13; +// In an actual implementation Item would be used to hold some value #pragma warning disable CS0168 - #region INCLUDE - public class BinaryTree +#region INCLUDE +public class BinaryTree +{ + public BinaryTree(T item) { - public BinaryTree(T item) - { - Item = item; - } + Item = item; + } - public T Item { get; set; } - public Pair> SubItems + public T Item { get; set; } + public Pair> SubItems + { + get { return _SubItems; } + set { - get { return _SubItems; } - set - { - #region HIGHLIGHT - IComparable first; - // ERROR: Cannot implicitly convert type... - //first = value.First; // Explicit cast required + #region HIGHLIGHT + IComparable first; + // ERROR: Cannot implicitly convert type... + //first = value.First; // Explicit cast required - //if(first.CompareTo(value.Second) < 0) - //{ - // // first is less than second - // //... - //} - //else - //{ - // // first and second are the same or - // // second is less than first - // //... - //} - _SubItems = value; - #endregion HIGHLIGHT - } + //if(first.CompareTo(value.Second) < 0) + //{ + // // first is less than second + // //... + //} + //else + //{ + // // first and second are the same or + // // second is less than first + // //... + //} + _SubItems = value; + #endregion HIGHLIGHT } - private Pair> _SubItems; } - #endregion INCLUDE -#pragma warning restore CS0168 + private Pair> _SubItems; } +#endregion INCLUDE +#pragma warning restore CS0168 + diff --git a/src/Chapter12/Listing12.21.NeedingTheTypeParameterToSupportAnInterfaceOrExceptionThrown.cs b/src/Chapter12/Listing12.21.NeedingTheTypeParameterToSupportAnInterfaceOrExceptionThrown.cs index c770a1115..ed476b3b1 100644 --- a/src/Chapter12/Listing12.21.NeedingTheTypeParameterToSupportAnInterfaceOrExceptionThrown.cs +++ b/src/Chapter12/Listing12.21.NeedingTheTypeParameterToSupportAnInterfaceOrExceptionThrown.cs @@ -1,61 +1,60 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_21; + +using System; +using Listing12_13; +#region INCLUDE +public class BinaryTree { - using System; - using Listing12_13; - #region INCLUDE - public class BinaryTree + public BinaryTree(T item) { - public BinaryTree(T item) - { - Item = item; - } + Item = item; + } - public T Item { get; set; } - public Pair?>? SubItems + public T Item { get; set; } + public Pair?>? SubItems + { + get { return _SubItems; } + set { - get { return _SubItems; } - set + switch (value) { - switch (value) - { - // Null handling removed for elucidation + // Null handling removed for elucidation - // Using C# 8.0 Pattern Matching. Switch to - // checking for null prior to C# 8.0 - #region EXCLUDE - case { First: null}: - // First is null - break; - case { Second: null }: - // Second is null - break; - #endregion EXCLUDE - case - { - #region HIGHLIGHT - First: {Item: IComparable first }, - #endregion HIGHLIGHT - Second: {Item: T second } }: + // Using C# 8.0 Pattern Matching. Switch to + // checking for null prior to C# 8.0 + #region EXCLUDE + case { First: null}: + // First is null + break; + case { Second: null }: + // Second is null + break; + #endregion EXCLUDE + case + { #region HIGHLIGHT - if (first.CompareTo(second) < 0) + First: {Item: IComparable first }, #endregion HIGHLIGHT - { - // first is less than second - } - else - { - // second is less than or equal to first - } - break; - default: - throw new InvalidCastException( - @$"Unable to sort the items as { - typeof(T) } does not support IComparable."); - }; - _SubItems = value; - } + Second: {Item: T second } }: + #region HIGHLIGHT + if (first.CompareTo(second) < 0) + #endregion HIGHLIGHT + { + // first is less than second + } + else + { + // second is less than or equal to first + } + break; + default: + throw new InvalidCastException( + @$"Unable to sort the items as { + typeof(T) } does not support IComparable."); + }; + _SubItems = value; } - private Pair?>? _SubItems; } - #endregion INCLUDE +private Pair?>? _SubItems; } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.22.DeclaringAnInterfaceConstraint.cs b/src/Chapter12/Listing12.22.DeclaringAnInterfaceConstraint.cs index c4ead753b..f27fd0299 100644 --- a/src/Chapter12/Listing12.22.DeclaringAnInterfaceConstraint.cs +++ b/src/Chapter12/Listing12.22.DeclaringAnInterfaceConstraint.cs @@ -1,66 +1,65 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_22 -{ - using System; - using Listing12_13; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_22; + +using System; +using Listing12_13; - #region INCLUDE - public class BinaryTree - #region HIGHLIGHT - where T : System.IComparable - #endregion HIGHLIGHT +#region INCLUDE +public class BinaryTree + #region HIGHLIGHT + where T : System.IComparable + #endregion HIGHLIGHT +{ + public BinaryTree(T item) { - public BinaryTree(T item) - { - Item = item; - } + Item = item; + } - public T Item { get; set; } - public Pair?> SubItems + public T Item { get; set; } + public Pair?> SubItems + { + get { return _SubItems; } + set { - get { return _SubItems; } - set + switch (value) { - switch (value) - { - // Null handling removed for elucidation + // Null handling removed for elucidation - // Using C# 8.0 Pattern Matching. Switch to - // checking for null prior to C# 8.0 - #region EXCLUDE - case { First: null }: - // First is null - break; - case { Second: null }: - // Second is null - break; - #endregion EXCLUDE - case + // Using C# 8.0 Pattern Matching. Switch to + // checking for null prior to C# 8.0 + #region EXCLUDE + case { First: null }: + // First is null + break; + case { Second: null }: + // Second is null + break; + #endregion EXCLUDE + case + { + #region HIGHLIGHT + First: { Item: T first }, + #endregion HIGHLIGHT + Second: { Item: T second } + }: + #region HIGHLIGHT + if (first.CompareTo(second) < 0) + #endregion HIGHLIGHT + { + // first is less than second + } + else { - #region HIGHLIGHT - First: { Item: T first }, - #endregion HIGHLIGHT - Second: { Item: T second } - }: - #region HIGHLIGHT - if (first.CompareTo(second) < 0) - #endregion HIGHLIGHT - { - // first is less than second - } - else - { - // second is less than or equal to first - } - break; - default: - throw new InvalidCastException( - @$"Unable to sort the items as { - typeof(T) } does not support IComparable."); - }; - _SubItems = value; - } + // second is less than or equal to first + } + break; + default: + throw new InvalidCastException( + @$"Unable to sort the items as { + typeof(T) } does not support IComparable."); + }; + _SubItems = value; } - private Pair?> _SubItems; } - #endregion INCLUDE + private Pair?> _SubItems; } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.23.DeclaringABaseClassConstraint.cs b/src/Chapter12/Listing12.23.DeclaringABaseClassConstraint.cs index 5f9d3b504..3483e464c 100644 --- a/src/Chapter12/Listing12.23.DeclaringABaseClassConstraint.cs +++ b/src/Chapter12/Listing12.23.DeclaringABaseClassConstraint.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_23; + +#region INCLUDE +public class EntityDictionary + : System.Collections.Generic.Dictionary + #region HIGHLIGHT + where TKey : notnull + where TValue : EntityBase + #endregion HIGHLIGHT +{ + // ... +} +#endregion INCLUDE +public class EntityBase { - #region INCLUDE - public class EntityDictionary - : System.Collections.Generic.Dictionary - #region HIGHLIGHT - where TKey : notnull - where TValue : EntityBase - #endregion HIGHLIGHT - { - // ... - } - #endregion INCLUDE - public class EntityBase - { - } } diff --git a/src/Chapter12/Listing12.24.DeclaringAGenericWithAMulticastDelegateConstraint.cs b/src/Chapter12/Listing12.24.DeclaringAGenericWithAMulticastDelegateConstraint.cs index 74b118092..460e57dfb 100644 --- a/src/Chapter12/Listing12.24.DeclaringAGenericWithAMulticastDelegateConstraint.cs +++ b/src/Chapter12/Listing12.24.DeclaringAGenericWithAMulticastDelegateConstraint.cs @@ -1,30 +1,29 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_31 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_31; + +public class Publisher { - public class Publisher + #region INCLUDE + static public object? InvokeAll( + object?[]? args, params TDelegate[] delegates) + // Constraint of type Action/Func not allowed + where TDelegate : System.MulticastDelegate { - #region INCLUDE - static public object? InvokeAll( - object?[]? args, params TDelegate[] delegates) - // Constraint of type Action/Func not allowed - where TDelegate : System.MulticastDelegate - { - switch (Delegate.Combine(delegates)) - { - case Action action: - action(); - return null; - case TDelegate result: - return result.DynamicInvoke(args); - default: - return null; - }; - } - #endregion INCLUDE + switch (Delegate.Combine(delegates)) + { + case Action action: + action(); + return null; + case TDelegate result: + return result.DynamicInvoke(args); + default: + return null; + }; + } + #endregion INCLUDE - static public void InvokeAll(params Action?[] actions) - { - Action? result = (Action?)Delegate.Combine(actions); - result?.Invoke(); - } + static public void InvokeAll(params Action?[] actions) + { + Action? result = (Action?)Delegate.Combine(actions); + result?.Invoke(); } } diff --git a/src/Chapter12/Listing12.25.SpecifyingTheTypeParameterAsAValueType.cs b/src/Chapter12/Listing12.25.SpecifyingTheTypeParameterAsAValueType.cs index 12800ab36..6943492f4 100644 --- a/src/Chapter12/Listing12.25.SpecifyingTheTypeParameterAsAValueType.cs +++ b/src/Chapter12/Listing12.25.SpecifyingTheTypeParameterAsAValueType.cs @@ -1,44 +1,43 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_24 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_24; + +using System; +#region INCLUDE +public struct Nullable : + IFormattable, IComparable, + IComparable>, INullable + #region HIGHLIGHT + where T : struct + #endregion HIGHLIGHT { - using System; - #region INCLUDE - public struct Nullable : - IFormattable, IComparable, - IComparable>, INullable - #region HIGHLIGHT - where T : struct - #endregion HIGHLIGHT + // ... + public static implicit operator Nullable(T value) => + new Nullable(value); + public static explicit operator T(Nullable value) => value!.Value; + #region EXCLUDE + public Nullable(T value) { // ... - public static implicit operator Nullable(T value) => - new Nullable(value); - public static explicit operator T(Nullable value) => value!.Value; - #region EXCLUDE - public Nullable(T value) - { - // ... - } - public T Value => throw new NotImplementedException(); - public string ToString(string? format, IFormatProvider? formatProvider) - { - throw new NotImplementedException(); - } + } + public T Value => throw new NotImplementedException(); + public string ToString(string? format, IFormatProvider? formatProvider) + { + throw new NotImplementedException(); + } - public int CompareTo(object? obj) - { - throw new NotImplementedException(); - } + public int CompareTo(object? obj) + { + throw new NotImplementedException(); + } - public int CompareTo(Nullable other) - { - throw new NotImplementedException(); - } + public int CompareTo(Nullable other) + { + throw new NotImplementedException(); + } - public bool IsNull - { - get { throw new NotImplementedException(); } - } - #endregion EXCLUDE + public bool IsNull + { + get { throw new NotImplementedException(); } } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.26.SpecifyingMultipleConstraints.cs b/src/Chapter12/Listing12.26.SpecifyingMultipleConstraints.cs index 3db641076..9e46515d9 100644 --- a/src/Chapter12/Listing12.26.SpecifyingMultipleConstraints.cs +++ b/src/Chapter12/Listing12.26.SpecifyingMultipleConstraints.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_25 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_25; + +using System; +using System.Collections.Generic; +using Listing12_23; +#region INCLUDE +public class EntityDictionary + : Dictionary + where TKey : IComparable, IFormattable + where TValue : EntityBase { - using System; - using System.Collections.Generic; - using Listing12_23; - #region INCLUDE - public class EntityDictionary - : Dictionary - where TKey : IComparable, IFormattable - where TValue : EntityBase - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.27.RequiringADefaultConstructorConstraint.cs b/src/Chapter12/Listing12.27.RequiringADefaultConstructorConstraint.cs index 4f15d2820..7012bdd21 100644 --- a/src/Chapter12/Listing12.27.RequiringADefaultConstructorConstraint.cs +++ b/src/Chapter12/Listing12.27.RequiringADefaultConstructorConstraint.cs @@ -1,39 +1,38 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_26 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_26; + +using System; +using System.Collections.Generic; +#region INCLUDE +public class EntityBase + where TKey: notnull { - using System; - using System.Collections.Generic; - #region INCLUDE - public class EntityBase - where TKey: notnull + public EntityBase(TKey key) { - public EntityBase(TKey key) - { - Key = key; - } - - public TKey Key { get; set; } + Key = key; } + + public TKey Key { get; set; } +} - public class EntityDictionary : - Dictionary - where TKey : IComparable, IFormattable - #region HIGHLIGHT - where TValue : EntityBase, new() - #endregion HIGHLIGHT +public class EntityDictionary : + Dictionary + where TKey : IComparable, IFormattable + #region HIGHLIGHT + where TValue : EntityBase, new() + #endregion HIGHLIGHT +{ + public TValue MakeValue(TKey key) { - public TValue MakeValue(TKey key) + #region HIGHLIGHT + TValue newEntity = new TValue { - #region HIGHLIGHT - TValue newEntity = new TValue - { - #endregion HIGHLIGHT - Key = key - }; - Add(newEntity.Key, newEntity); - return newEntity; - } - - // ... + #endregion HIGHLIGHT + Key = key + }; + Add(newEntity.Key, newEntity); + return newEntity; } - #endregion INCLUDE + + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.28.ConstraintsCanOnlyBeSpecifiedForDefaultConstructors.cs b/src/Chapter12/Listing12.28.ConstraintsCanOnlyBeSpecifiedForDefaultConstructors.cs index 5e917c547..fed4dcfa4 100644 --- a/src/Chapter12/Listing12.28.ConstraintsCanOnlyBeSpecifiedForDefaultConstructors.cs +++ b/src/Chapter12/Listing12.28.ConstraintsCanOnlyBeSpecifiedForDefaultConstructors.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_28 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_28; + +public class Program { - public class Program + /* + #region INCLUDE + public TValue New(TKey key) { - /* - #region INCLUDE - public TValue New(TKey key) - { - // Error: 'TValue': Cannot provide arguments - // when creating an instance of a variable type - TValue newEntity = null; - // newEntity = new TValue(key); - Add(newEntity.Key, newEntity); - return newEntity; - } - #endregion INCLUDE - */ + // Error: 'TValue': Cannot provide arguments + // when creating an instance of a variable type + TValue newEntity = null; + // newEntity = new TValue(key); + Add(newEntity.Key, newEntity); + return newEntity; } + #endregion INCLUDE + */ } diff --git a/src/Chapter12/Listing12.29.UsingAFactoryInterfaceInPlaceOfAConstructorConstraint.cs b/src/Chapter12/Listing12.29.UsingAFactoryInterfaceInPlaceOfAConstructorConstraint.cs index 34420522c..acec82f6f 100644 --- a/src/Chapter12/Listing12.29.UsingAFactoryInterfaceInPlaceOfAConstructorConstraint.cs +++ b/src/Chapter12/Listing12.29.UsingAFactoryInterfaceInPlaceOfAConstructorConstraint.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_29 -{ - using System.Collections.Generic; - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_29; - #region INCLUDE - public class EntityBase - { - #region HIGHLIGHT - public EntityBase(TKey key) - { - Key = key; - } - #endregion HIGHLIGHT - public TKey Key { get; set; } - } +using System.Collections.Generic; +using System; - public class EntityDictionary : - Dictionary - where TKey : IComparable, IFormattable - #region HIGHLIGHT - where TValue : EntityBase - where TFactory : IEntityFactory, new() - #endregion HIGHLIGHT +#region INCLUDE +public class EntityBase +{ + #region HIGHLIGHT + public EntityBase(TKey key) { - // ... - - public TValue New(TKey key) - { - TFactory factory = new TFactory(); - #region HIGHLIGHT - TValue newEntity = factory.CreateNew(key); - #endregion HIGHLIGHT - Add(newEntity.Key, newEntity); - return newEntity; - } - //... + Key = key; } + #endregion HIGHLIGHT + public TKey Key { get; set; } +} +public class EntityDictionary : + Dictionary + where TKey : IComparable, IFormattable #region HIGHLIGHT - public interface IEntityFactory + where TValue : EntityBase + where TFactory : IEntityFactory, new() + #endregion HIGHLIGHT +{ + // ... + + public TValue New(TKey key) { - TValue CreateNew(TKey key); + TFactory factory = new TFactory(); + #region HIGHLIGHT + TValue newEntity = factory.CreateNew(key); + #endregion HIGHLIGHT + Add(newEntity.Key, newEntity); + return newEntity; } - #endregion HIGHLIGHT - #endregion INCLUDE + //... +} + +#region HIGHLIGHT +public interface IEntityFactory +{ + TValue CreateNew(TKey key); } +#endregion HIGHLIGHT +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.30.DeclaringAnEntityToBeUsedInEntityDictionary.cs b/src/Chapter12/Listing12.30.DeclaringAnEntityToBeUsedInEntityDictionary.cs index 0d764c916..ce3d0a443 100644 --- a/src/Chapter12/Listing12.30.DeclaringAnEntityToBeUsedInEntityDictionary.cs +++ b/src/Chapter12/Listing12.30.DeclaringAnEntityToBeUsedInEntityDictionary.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_30 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_30; + +using System; +using Listing12_29; +#region INCLUDE +public class Order : EntityBase { - using System; - using Listing12_29; - #region INCLUDE - public class Order : EntityBase + public Order(Guid key) : + base(key) { - public Order(Guid key) : - base(key) - { - // ... - } + // ... } +} - public class OrderFactory : IEntityFactory +public class OrderFactory : IEntityFactory +{ + public Order CreateNew(Guid key) { - public Order CreateNew(Guid key) - { - return new Order(key); - } + return new Order(key); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.31.InheritedConstraintsSpecifiedExplicitly.cs b/src/Chapter12/Listing12.31.InheritedConstraintsSpecifiedExplicitly.cs index 59939bb84..a21ec0210 100644 --- a/src/Chapter12/Listing12.31.InheritedConstraintsSpecifiedExplicitly.cs +++ b/src/Chapter12/Listing12.31.InheritedConstraintsSpecifiedExplicitly.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_31 -{ - using System; - #region INCLUDE - public class EntityBase where T : IComparable - { - // ... - } +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_31; - // ERROR: - // The type 'U' must be convertible to 'System.IComparable' - // to use it as parameter 'T' in the generic type or - // method - // class Entity : EntityBase - // { - // ... - // } - #endregion INCLUDE +using System; +#region INCLUDE +public class EntityBase where T : IComparable +{ + // ... } + +// ERROR: +// The type 'U' must be convertible to 'System.IComparable' +// to use it as parameter 'T' in the generic type or +// method +// class Entity : EntityBase +// { +// ... +// } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.32.RepeatingInheritedOnVirtualMembersIsProhibited.cs b/src/Chapter12/Listing12.32.RepeatingInheritedOnVirtualMembersIsProhibited.cs index 8ca0dda0b..6535f9099 100644 --- a/src/Chapter12/Listing12.32.RepeatingInheritedOnVirtualMembersIsProhibited.cs +++ b/src/Chapter12/Listing12.32.RepeatingInheritedOnVirtualMembersIsProhibited.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_32 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_32; + +using System; +#region INCLUDE +public class EntityBase { - using System; - #region INCLUDE - public class EntityBase + public virtual void Method(T t) + where T : IComparable { - public virtual void Method(T t) - where T : IComparable - { - // ... - } + // ... } - public class Order : EntityBase +} +public class Order : EntityBase +{ + public override void Method(T t) + // Constraints may not be repeated on overriding + // members + // where T : IComparable { - public override void Method(T t) - // Constraints may not be repeated on overriding - // members - // where T : IComparable - { - // ... - } + // ... } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.33.ConstraintExpressionsCannotRequireOperators.cs b/src/Chapter12/Listing12.33.ConstraintExpressionsCannotRequireOperators.cs index 7efa89605..577082b54 100644 --- a/src/Chapter12/Listing12.33.ConstraintExpressionsCannotRequireOperators.cs +++ b/src/Chapter12/Listing12.33.ConstraintExpressionsCannotRequireOperators.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_33 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_33; + +/* +#region INCLUDE +public abstract class MathEx { - /* - #region INCLUDE - public abstract class MathEx + public static T Add(T first, T second) { - public static T Add(T first, T second) - { - // Error: Operator '+' cannot be applied to - // operands of type 'T' and 'T' - #region HIGHLIGHT - // return first + second; - #endregion HIGHLIGHT - } + // Error: Operator '+' cannot be applied to + // operands of type 'T' and 'T' + #region HIGHLIGHT + // return first + second; + #endregion HIGHLIGHT } - #endregion INCLUDE - */ } +#endregion INCLUDE +*/ diff --git a/src/Chapter12/Listing12.34.CombiningConstraintsUsingOrRelationshipNotAllowed.cs b/src/Chapter12/Listing12.34.CombiningConstraintsUsingOrRelationshipNotAllowed.cs index 33e10c1a0..00dc3ec99 100644 --- a/src/Chapter12/Listing12.34.CombiningConstraintsUsingOrRelationshipNotAllowed.cs +++ b/src/Chapter12/Listing12.34.CombiningConstraintsUsingOrRelationshipNotAllowed.cs @@ -1,11 +1,10 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_30 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_30; + +#region INCLUDE +public class BinaryTree + // Error: OR is not supported + // where T: System.IComparable || System.IFormattable { - #region INCLUDE - public class BinaryTree - // Error: OR is not supported - // where T: System.IComparable || System.IFormattable - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.35.DefiningGenericMethods.cs b/src/Chapter12/Listing12.35.DefiningGenericMethods.cs index ea282d1a0..e1994ebf6 100644 --- a/src/Chapter12/Listing12.35.DefiningGenericMethods.cs +++ b/src/Chapter12/Listing12.35.DefiningGenericMethods.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_35 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_35; + +using System; - #region INCLUDE - public static class MathEx +#region INCLUDE +public static class MathEx +{ + public static T Max(T first, params T[] values) + where T : IComparable { - public static T Max(T first, params T[] values) - where T : IComparable + T maximum = first; + foreach(T item in values) { - T maximum = first; - foreach(T item in values) + if(item.CompareTo(maximum) > 0) { - if(item.CompareTo(maximum) > 0) - { - maximum = item; - } + maximum = item; } - return maximum; } + return maximum; + } - public static T Min(T first, params T[] values) - where T : IComparable - { - T minimum = first; + public static T Min(T first, params T[] values) + where T : IComparable + { + T minimum = first; - foreach(T item in values) + foreach(T item in values) + { + if(item.CompareTo(minimum) < 0) { - if(item.CompareTo(minimum) < 0) - { - minimum = item; - } + minimum = item; } - return minimum; } + return minimum; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.36.SpecifyingTheTypeParameterExplicitly.cs b/src/Chapter12/Listing12.36.SpecifyingTheTypeParameterExplicitly.cs index fcd40ef34..4b1951e23 100644 --- a/src/Chapter12/Listing12.36.SpecifyingTheTypeParameterExplicitly.cs +++ b/src/Chapter12/Listing12.36.SpecifyingTheTypeParameterExplicitly.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_36 -{ - using System; - using Listing12_35; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_36; + +using System; +using Listing12_35; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.WriteLine( - MathEx.Max(7, 490)); - Console.WriteLine( - MathEx.Min("R.O.U.S.", "Fireswamp")); - #endregion INCLUDE - } + #region INCLUDE + Console.WriteLine( + MathEx.Max(7, 490)); + Console.WriteLine( + MathEx.Min("R.O.U.S.", "Fireswamp")); + #endregion INCLUDE } } diff --git a/src/Chapter12/Listing12.37.InferringTheTypeParameter.cs b/src/Chapter12/Listing12.37.InferringTheTypeParameter.cs index c784127c9..b48dd515d 100644 --- a/src/Chapter12/Listing12.37.InferringTheTypeParameter.cs +++ b/src/Chapter12/Listing12.37.InferringTheTypeParameter.cs @@ -1,18 +1,17 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_37 -{ - using System; - using Listing12_35; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_37; + +using System; +using Listing12_35; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - Console.WriteLine( - MathEx.Max(7, 490)); // No type arguments! - Console.WriteLine( - MathEx.Min("R.O.U.S'", "Fireswamp")); - #endregion INCLUDE - } + #region INCLUDE + Console.WriteLine( + MathEx.Max(7, 490)); // No type arguments! + Console.WriteLine( + MathEx.Min("R.O.U.S'", "Fireswamp")); + #endregion INCLUDE } } diff --git a/src/Chapter12/Listing12.38.SpecifyingConstraintsOnGenericMethods.cs b/src/Chapter12/Listing12.38.SpecifyingConstraintsOnGenericMethods.cs index e0d33e03c..052a88105 100644 --- a/src/Chapter12/Listing12.38.SpecifyingConstraintsOnGenericMethods.cs +++ b/src/Chapter12/Listing12.38.SpecifyingConstraintsOnGenericMethods.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_38 -{ - using System; - using Listing12_22; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_38; + +using System; +using Listing12_22; - #region INCLUDE - public class ConsoleTreeControl +#region INCLUDE +public class ConsoleTreeControl +{ + // Generic method Show + public static void Show(BinaryTree tree, int indent) + #region HIGHLIGHT + where T : IComparable + #endregion HIGHLIGHT { - // Generic method Show - public static void Show(BinaryTree tree, int indent) - #region HIGHLIGHT - where T : IComparable - #endregion HIGHLIGHT - { - Console.WriteLine("\n{0}{1}", - "+ --".PadLeft(5 * indent, ' '), - tree.Item.ToString()); - if(tree.SubItems.First != null) - Show(tree.SubItems.First, indent + 1); - if(tree.SubItems.Second != null) - Show(tree.SubItems.Second, indent + 1); - } + Console.WriteLine("\n{0}{1}", + "+ --".PadLeft(5 * indent, ' '), + tree.Item.ToString()); + if(tree.SubItems.First != null) + Show(tree.SubItems.First, indent + 1); + if(tree.SubItems.Second != null) + Show(tree.SubItems.Second, indent + 1); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.39.BinaryTreeRequiringIComparableTypeParameters.cs b/src/Chapter12/Listing12.39.BinaryTreeRequiringIComparableTypeParameters.cs index e76c439da..2c0ba60c3 100644 --- a/src/Chapter12/Listing12.39.BinaryTreeRequiringIComparableTypeParameters.cs +++ b/src/Chapter12/Listing12.39.BinaryTreeRequiringIComparableTypeParameters.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_39 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_39; + +#region INCLUDE +public class BinaryTree + #region HIGHLIGHT + where T : System.IComparable + #endregion HIGHLIGHT { - #region INCLUDE - public class BinaryTree - #region HIGHLIGHT - where T : System.IComparable - #endregion HIGHLIGHT - { - //... - } - #endregion INCLUDE + //... } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.40.ConversionBetweenGenericsWithDifferentTypeParameters.cs b/src/Chapter12/Listing12.40.ConversionBetweenGenericsWithDifferentTypeParameters.cs index 3edb6e9bf..93b52f9f3 100644 --- a/src/Chapter12/Listing12.40.ConversionBetweenGenericsWithDifferentTypeParameters.cs +++ b/src/Chapter12/Listing12.40.ConversionBetweenGenericsWithDifferentTypeParameters.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_40 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_40; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - /* - #region INCLUDE - // ... - // Error: Cannot convert type ... - Pair pair = (Pair)new Pair(); - IPair duple = (IPair)new Pair(); - #endregion INCLUDE - */ - } + /* + #region INCLUDE + // ... + // Error: Cannot convert type ... + Pair pair = (Pair)new Pair(); + IPair duple = (IPair)new Pair(); + #endregion INCLUDE + */ } } diff --git a/src/Chapter12/Listing12.41.PreventingCovarianceMaintainsHomogeneity.cs b/src/Chapter12/Listing12.41.PreventingCovarianceMaintainsHomogeneity.cs index 1e751a3ea..ef64ca9d3 100644 --- a/src/Chapter12/Listing12.41.PreventingCovarianceMaintainsHomogeneity.cs +++ b/src/Chapter12/Listing12.41.PreventingCovarianceMaintainsHomogeneity.cs @@ -1,26 +1,25 @@ using AddisonWesley.Michaelis.EssentialCSharp.Chapter08.Listing08_05; using AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_11; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_41 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_41; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - // ... - Contact contact1 = new Contact("Princess Buttercup"); - Contact contact2 = new Contact("Inigo Montoya"); - Pair contacts = new Pair(contact1, contact2); + #region INCLUDE + // ... + Contact contact1 = new Contact("Princess Buttercup"); + Contact contact2 = new Contact("Inigo Montoya"); + Pair contacts = new Pair(contact1, contact2); - #region HIGHLIGHT - // This gives an error: Cannot convert type ... - // But suppose it did not - // IPair pdaPair = (IPair) contacts; - // This is perfectly legal, but not type-safe - // pair.First = new Address("123 Sesame Street"); - #endregion HIGHLIGHT - #endregion INCLUDE - } + #region HIGHLIGHT + // This gives an error: Cannot convert type ... + // But suppose it did not + // IPair pdaPair = (IPair) contacts; + // This is perfectly legal, but not type-safe + // pair.First = new Address("123 Sesame Street"); + #endregion HIGHLIGHT + #endregion INCLUDE } } diff --git a/src/Chapter12/Listing12.42.PotentiallyPossibleCovariance.cs b/src/Chapter12/Listing12.42.PotentiallyPossibleCovariance.cs index 929042f2e..200c413b6 100644 --- a/src/Chapter12/Listing12.42.PotentiallyPossibleCovariance.cs +++ b/src/Chapter12/Listing12.42.PotentiallyPossibleCovariance.cs @@ -1,65 +1,64 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_42 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_42; + +#region INCLUDE +interface IReadOnlyPair { - #region INCLUDE - interface IReadOnlyPair - { - T First { get; } - T Second { get; } - } + T First { get; } + T Second { get; } +} - interface IPair - { - T First { get; set; } - T Second { get; set; } - } +interface IPair +{ + T First { get; set; } + T Second { get; set; } +} - public struct Pair : IPair, IReadOnlyPair +public struct Pair : IPair, IReadOnlyPair +{ + #region EXCLUDE + #region Generated Interface Stub + public T First { - #region EXCLUDE - #region Generated Interface Stub - public T First + get { - get - { - throw new System.NotImplementedException(); - } - set - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } - - public T Second + set { - get - { - throw new System.NotImplementedException(); - } - set - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } - #endregion Generated Interface Stub - #endregion EXCLUDE } - public class Program + public T Second { - static void Main() + get + { + throw new System.NotImplementedException(); + } + set { - // Error: Only theoretically possible without - // the out type parameter modifier - #region HIGHLIGHT - //Pair contacts = - // new Pair( - // new Contact("Princess Buttercup"), - // new Contact("Inigo Montoya")); - //IReadOnlyPair pair = contacts; - //PdaItem pdaItem1 = pair.First; - //PdaItem pdaItem2 = pair.Second; - #endregion HIGHLIGHT + throw new System.NotImplementedException(); } } - #endregion INCLUDE + #endregion Generated Interface Stub + #endregion EXCLUDE +} + +public class Program +{ + static void Main() + { + // Error: Only theoretically possible without + // the out type parameter modifier + #region HIGHLIGHT + //Pair contacts = + // new Pair( + // new Contact("Princess Buttercup"), + // new Contact("Inigo Montoya")); + //IReadOnlyPair pair = contacts; + //PdaItem pdaItem1 = pair.First; + //PdaItem pdaItem2 = pair.Second; + #endregion HIGHLIGHT + } } +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.43.CovarianceUsingTheOutTypeParameterModifier.cs b/src/Chapter12/Listing12.43.CovarianceUsingTheOutTypeParameterModifier.cs index 03ae3da02..69e28ce06 100644 --- a/src/Chapter12/Listing12.43.CovarianceUsingTheOutTypeParameterModifier.cs +++ b/src/Chapter12/Listing12.43.CovarianceUsingTheOutTypeParameterModifier.cs @@ -1,95 +1,93 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_43 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_43; + +using Chapter08.Listing08_02; +using Contact = Chapter12.Contact; + +#region INCLUDE +#region HIGHLIGHT +interface IReadOnlyPair +#endregion HIGHLIGHT { - using Chapter08.Listing08_02; - using Contact = Chapter12.Contact; + T First { get; } + T Second { get; } +} +#endregion INCLUDE - #region INCLUDE - #region HIGHLIGHT - interface IReadOnlyPair - #endregion HIGHLIGHT - { - T First { get; } - T Second { get; } - } - #endregion INCLUDE +interface IPair +{ + T First { get; set; } + T Second { get; set; } +} - interface IPair +public struct Pair : IPair, IReadOnlyPair +{ + public Pair(T first, T second) { - T First { get; set; } - T Second { get; set; } + _First = first; + _ReadOnlyFirst = first; + _Second = second; + _ReadOnlySecond = second; } - public struct Pair : IPair, IReadOnlyPair - { - public Pair(T first, T second) - { - _First = first; - _ReadOnlyFirst = first; - _Second = second; - _ReadOnlySecond = second; - } - - // ... + // ... - T IPair.First + T IPair.First + { + get { - get - { - return _First; - } - set - { - _First = value; - } + return _First; } - private T _First; - - T IReadOnlyPair.Second + set { - get - { - return _ReadOnlySecond; - } + _First = value; } - private T _ReadOnlySecond; + } + private T _First; - T IReadOnlyPair.First + T IReadOnlyPair.Second + { + get { - get - { - return _ReadOnlyFirst; - } + return _ReadOnlySecond; } - private T _ReadOnlyFirst; + } + private T _ReadOnlySecond; - T IPair.Second + T IReadOnlyPair.First + { + get { - get - { - return _Second; - } - set - { - _Second = value; - } + return _ReadOnlyFirst; } - private T _Second; } + private T _ReadOnlyFirst; - class Program + T IPair.Second { - static void Main() + get { - // Allowed in C# 4.0 - Pair contacts = - new Pair( - new Contact("Princess Buttercup"), - new Contact("Inigo Montoya")); - IReadOnlyPair pair = contacts; - PdaItem pdaItem1 = pair.First; - PdaItem pdaItem2 = pair.Second; + return _Second; + } + set + { + _Second = value; } } + private T _Second; +} +class Program +{ + static void Main() + { + // Allowed in C# 4.0 + Pair contacts = + new Pair( + new Contact("Princess Buttercup"), + new Contact("Inigo Montoya")); + IReadOnlyPair pair = contacts; + PdaItem pdaItem1 = pair.First; + PdaItem pdaItem2 = pair.Second; + } } diff --git a/src/Chapter12/Listing12.44.ContravarianceUsingTheInTypeParameterModifier.cs b/src/Chapter12/Listing12.44.ContravarianceUsingTheInTypeParameterModifier.cs index aec3980e8..d54697b05 100644 --- a/src/Chapter12/Listing12.44.ContravarianceUsingTheInTypeParameterModifier.cs +++ b/src/Chapter12/Listing12.44.ContravarianceUsingTheInTypeParameterModifier.cs @@ -1,50 +1,49 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_44 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_44; + +#region INCLUDE +class Fruit { } +class Apple : Fruit { } +class Orange : Fruit { } + +#region HIGHLIGHT +interface ICompareThings { - #region INCLUDE - class Fruit { } - class Apple : Fruit { } - class Orange : Fruit { } + bool FirstIsBetter(T t1, T t2); +} +#endregion HIGHLIGHT - #region HIGHLIGHT - interface ICompareThings - { - bool FirstIsBetter(T t1, T t2); - } - #endregion HIGHLIGHT +public class Program +{ - public class Program + private class FruitComparer : ICompareThings { - - private class FruitComparer : ICompareThings + #region EXCLUDE + #region Generated Interface Stub + public bool FirstIsBetter(Fruit t1, Fruit t2) { - #region EXCLUDE - #region Generated Interface Stub - public bool FirstIsBetter(Fruit t1, Fruit t2) - { - throw new System.NotImplementedException(); - } - #endregion Generated Interface Stub - #endregion EXCLUDE + throw new System.NotImplementedException(); } - static void Main() - { - ICompareThings fc = new FruitComparer(); + #endregion Generated Interface Stub + #endregion EXCLUDE + } + static void Main() + { + ICompareThings fc = new FruitComparer(); - Apple apple1 = new Apple(); - Apple apple2 = new Apple(); - Orange orange = new Orange(); + Apple apple1 = new Apple(); + Apple apple2 = new Apple(); + Orange orange = new Orange(); - // A fruit comparer can compare apples and oranges: - bool b1 = fc.FirstIsBetter(apple1, orange); - // or apples and apples: - bool b2 = fc.FirstIsBetter(apple1, apple2); - // This is legal because the interface is - // contravariant. - ICompareThings ac = fc; - // This is really a fruit comparer, so it can - // still compare two apples - bool b3 = ac.FirstIsBetter(apple1, apple2); - } + // A fruit comparer can compare apples and oranges: + bool b1 = fc.FirstIsBetter(apple1, orange); + // or apples and apples: + bool b2 = fc.FirstIsBetter(apple1, apple2); + // This is legal because the interface is + // contravariant. + ICompareThings ac = fc; + // This is really a fruit comparer, so it can + // still compare two apples + bool b3 = ac.FirstIsBetter(apple1, apple2); } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.46.StackDeclaration.cs b/src/Chapter12/Listing12.46.StackDeclaration.cs index 58c461848..933b1acdd 100644 --- a/src/Chapter12/Listing12.46.StackDeclaration.cs +++ b/src/Chapter12/Listing12.46.StackDeclaration.cs @@ -1,17 +1,16 @@ // Justification: Only showing partial implementaiton. #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_46 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_46; + +using System; +#region INCLUDE +public class Stack where T : IComparable { - using System; - #region INCLUDE - public class Stack where T : IComparable - { - private T[] _Items; - // rest of the class here - #region EXCLUDE - public T[] Items { get => _Items; set => _Items = value; } - #endregion EXCLUDE - } - #endregion INCLUDE -} \ No newline at end of file + private T[] _Items; + // rest of the class here + #region EXCLUDE + public T[] Items { get => _Items; set => _Items = value; } + #endregion EXCLUDE +} +#endregion INCLUDE diff --git a/src/Chapter12/Listing12.47.CILCodeForStack.cs b/src/Chapter12/Listing12.47.CILCodeForStack.cs index 099b99a85..c82235ab2 100644 --- a/src/Chapter12/Listing12.47.CILCodeForStack.cs +++ b/src/Chapter12/Listing12.47.CILCodeForStack.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_47 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_47; + +// CIL CODE BELOW +/* +#region INCLUDE +.class private auto ansi beforefieldinit +Stack'1<([mscorlib]System.IComparable)T> +extends [mscorlib]System.Object { - // CIL CODE BELOW - /* - #region INCLUDE - .class private auto ansi beforefieldinit - Stack'1<([mscorlib]System.IComparable)T> - extends [mscorlib]System.Object - { - ... - } - #endregion INCLUDE - */ + ... } +#endregion INCLUDE +*/ diff --git a/src/Chapter12/Listing12.48.CILWithExclamationPointNotation.cs b/src/Chapter12/Listing12.48.CILWithExclamationPointNotation.cs index efdbb6916..ffce414c4 100644 --- a/src/Chapter12/Listing12.48.CILWithExclamationPointNotation.cs +++ b/src/Chapter12/Listing12.48.CILWithExclamationPointNotation.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_48 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_48; + +// CIL CODE BELOW +/* +#region INCLUDE +.class public auto ansi beforefieldinit + 'Stack'1'<([mscorlib]System.IComparable) T> + extends [mscorlib]System.Object { - // CIL CODE BELOW - /* - #region INCLUDE - .class public auto ansi beforefieldinit - 'Stack'1'<([mscorlib]System.IComparable) T> - extends [mscorlib]System.Object - { - #region HIGHLIGHT - .field private !0[ ] _Items - #endregion HIGHLIGHT - ... - } - #endregion INCLUDE - */ +#region HIGHLIGHT + .field private !0[ ] _Items +#endregion HIGHLIGHT + ... } +#endregion INCLUDE +*/ diff --git a/src/Chapter12/Listing12.49.StackIntDefinition.cs b/src/Chapter12/Listing12.49.StackIntDefinition.cs index 98c339c57..2affd30e0 100644 --- a/src/Chapter12/Listing12.49.StackIntDefinition.cs +++ b/src/Chapter12/Listing12.49.StackIntDefinition.cs @@ -2,17 +2,16 @@ #pragma warning disable CS0168 // Variable is declared but never used -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_49 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_49; + +public class Program { - public class Program + static private void Main() { - static private void Main() - { - #region INCLUDE - Stack stack; - #endregion INCLUDE + #region INCLUDE + Stack stack; + #endregion INCLUDE - // ... - } + // ... } } diff --git a/src/Chapter12/Listing12.50.DeclaringVariablesOfTypeStack.cs b/src/Chapter12/Listing12.50.DeclaringVariablesOfTypeStack.cs index 6c09d73ab..b51b4d664 100644 --- a/src/Chapter12/Listing12.50.DeclaringVariablesOfTypeStack.cs +++ b/src/Chapter12/Listing12.50.DeclaringVariablesOfTypeStack.cs @@ -1,10 +1,9 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_50 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_50; + +public class Program { - public class Program - { - #region INCLUDE - Stack stackOne = new Stack(); - Stack stackTwo = new Stack(); - #endregion INCLUDE - } + #region INCLUDE + Stack stackOne = new Stack(); + Stack stackTwo = new Stack(); + #endregion INCLUDE } diff --git a/src/Chapter13/Listing13.01.BubbleSortMethod.cs b/src/Chapter13/Listing13.01.BubbleSortMethod.cs index 445920987..825867680 100644 --- a/src/Chapter13/Listing13.01.BubbleSortMethod.cs +++ b/src/Chapter13/Listing13.01.BubbleSortMethod.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_01; + +#region INCLUDE +public static class SimpleSort1 { - #region INCLUDE - public static class SimpleSort1 + public static void BubbleSort(int[] items) { - public static void BubbleSort(int[] items) - { - int i; - int j; - int temp; + int i; + int j; + int temp; - if(items == null) - { - return; - } + if(items == null) + { + return; + } - for(i = items.Length - 1; i >= 0; i--) + for(i = items.Length - 1; i >= 0; i--) + { + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(items[j - 1] > items[j]) { - if(items[j - 1] > items[j]) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } - // ... } - #endregion INCLUDE -} \ No newline at end of file + // ... +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.02.BubbleSortMethodAscendingOrDescending.cs b/src/Chapter13/Listing13.02.BubbleSortMethodAscendingOrDescending.cs index 5f7029300..0075b1879 100644 --- a/src/Chapter13/Listing13.02.BubbleSortMethodAscendingOrDescending.cs +++ b/src/Chapter13/Listing13.02.BubbleSortMethodAscendingOrDescending.cs @@ -1,58 +1,57 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_02; + +#region INCLUDE +public class SimpleSort2 { - #region INCLUDE - public class SimpleSort2 + public enum SortType + { + Ascending, + Descending + } + + #region HIGHLIGHT + public static void BubbleSort(int[] items, SortType sortOrder) + #endregion HIGHLIGHT { - public enum SortType + int i; + int j; + int temp; + + if(items == null) { - Ascending, - Descending + return; } - #region HIGHLIGHT - public static void BubbleSort(int[] items, SortType sortOrder) - #endregion HIGHLIGHT + for(i = items.Length - 1; i >= 0; i--) { - int i; - int j; - int temp; - - if(items == null) + for(j = 1; j <= i; j++) { - return; - } - for(i = items.Length - 1; i >= 0; i--) - { - for(j = 1; j <= i; j++) + bool swap = false; + switch(sortOrder) { + #region HIGHLIGHT + case SortType.Ascending: + swap = items[j - 1] > items[j]; + #endregion HIGHLIGHT + break; - bool swap = false; - switch(sortOrder) - { - #region HIGHLIGHT - case SortType.Ascending: - swap = items[j - 1] > items[j]; - #endregion HIGHLIGHT - break; - - #region HIGHLIGHT - case SortType.Descending: - swap = items[j - 1] < items[j]; - #endregion HIGHLIGHT - break; - } + #region HIGHLIGHT + case SortType.Descending: + swap = items[j - 1] < items[j]; + #endregion HIGHLIGHT + break; + } - if(swap) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + if(swap) + { + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } - // ... } - #endregion INCLUDE -} \ No newline at end of file + // ... +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.03.BubbleSortMethodWithDelegateParameter.cs b/src/Chapter13/Listing13.03.BubbleSortMethodWithDelegateParameter.cs index 389907c43..9943272a9 100644 --- a/src/Chapter13/Listing13.03.BubbleSortMethodWithDelegateParameter.cs +++ b/src/Chapter13/Listing13.03.BubbleSortMethodWithDelegateParameter.cs @@ -1,46 +1,45 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_03; + +using System; +#region INCLUDE +public class DelegateSample { - using System; - #region INCLUDE - public class DelegateSample + // ... + + #region HIGHLIGHT + public static void BubbleSort( + #endregion HIGHLIGHT + int[] items, Func compare) { - // ... + int i; + int j; + int temp; - #region HIGHLIGHT - public static void BubbleSort( - #endregion HIGHLIGHT - int[] items, Func compare) + if(compare == null) { - int i; - int j; - int temp; - - if(compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } + throw new ArgumentNullException(nameof(compare)); + } - if(items == null) - { - return; - } + if(items == null) + { + return; + } - for(i = items.Length - 1; i >= 0; i--) + for(i = items.Length - 1; i >= 0; i--) + { + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + #region HIGHLIGHT + if (compare(items[j - 1], items[j])) + #endregion HIGHLIGHT { - #region HIGHLIGHT - if (compare(items[j - 1], items[j])) - #endregion HIGHLIGHT - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } - // ... } - #endregion INCLUDE -} \ No newline at end of file + // ... +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.04.FuncAndActionDelegateDeclarations.cs b/src/Chapter13/Listing13.04.FuncAndActionDelegateDeclarations.cs index 3b2e99443..448957f00 100644 --- a/src/Chapter13/Listing13.04.FuncAndActionDelegateDeclarations.cs +++ b/src/Chapter13/Listing13.04.FuncAndActionDelegateDeclarations.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_04 -{ - /* - #region INCLUDE - public delegate void Action(); - public delegate void Action(T arg); - public delegate void Action( - T1 arg1, T2 arg2); - public delegate void Action( - T1 arg1, T2 arg2, T3 arg3); - public delegate void Action( - T1 arg1, T2 arg2, T3 arg3, T4 arg4); +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_04; - ... +/* +#region INCLUDE +public delegate void Action(); +public delegate void Action(T arg); +public delegate void Action( + T1 arg1, T2 arg2); +public delegate void Action( + T1 arg1, T2 arg2, T3 arg3); +public delegate void Action( + T1 arg1, T2 arg2, T3 arg3, T4 arg4); - public delegate void Action< - in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, - in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>( - T1 arg1, T2 arg2, T3 arg3, T4 arg4, - T5 arg5, T6 arg6, T7 arg7, T8 arg8, - T9 arg9, T10 arg10, T11 arg11, T12 arg12, - T13 arg13, T14 arg14, T15 arg15, T16 arg16); + ... - public delegate TResult Func(); - public delegate TResult Func(T arg); - public delegate TResult Func( - T1 arg1, T2 arg2); - public delegate TResult Func( - T1 arg1, T2 arg2, T3 arg3); - public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); +public delegate void Action< + in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, + in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>( + T1 arg1, T2 arg2, T3 arg3, T4 arg4, + T5 arg5, T6 arg6, T7 arg7, T8 arg8, + T9 arg9, T10 arg10, T11 arg11, T12 arg12, + T13 arg13, T14 arg14, T15 arg15, T16 arg16); - ... +public delegate TResult Func(); +public delegate TResult Func(T arg); +public delegate TResult Func( + T1 arg1, T2 arg2); +public delegate TResult Func( + T1 arg1, T2 arg2, T3 arg3); +public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); - public delegate TResult Func< - in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, - in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, - out TResult>( - T1 arg1, T2 arg2, T3 arg3, T4 arg4, - T5 arg5, T6 arg6, T7 arg7, T8 arg8, - T9 arg9, T10 arg10, T11 arg11, T12 arg12, - T13 arg13, T14 arg14, T15 arg15, T16 arg16); + ... - public delegate bool Predicate( T obj) - #endregion INCLUDE - */ -} \ No newline at end of file +public delegate TResult Func< + in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, + in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, + out TResult>( + T1 arg1, T2 arg2, T3 arg3, T4 arg4, + T5 arg5, T6 arg6, T7 arg7, T8 arg8, + T9 arg9, T10 arg10, T11 arg11, T12 arg12, + T13 arg13, T14 arg14, T15 arg15, T16 arg16); + +public delegate bool Predicate( T obj) +#endregion INCLUDE +*/ \ No newline at end of file diff --git a/src/Chapter13/Listing13.05.DeclaringADelegateType.cs b/src/Chapter13/Listing13.05.DeclaringADelegateType.cs index 2adff362b..15a3de8e9 100644 --- a/src/Chapter13/Listing13.05.DeclaringADelegateType.cs +++ b/src/Chapter13/Listing13.05.DeclaringADelegateType.cs @@ -1,7 +1,6 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_05 -{ - #region INCLUDE - public delegate bool Comparer( - int first, int second); - #endregion INCLUDE -} \ No newline at end of file +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_05; + +#region INCLUDE +public delegate bool Comparer( + int first, int second); +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.06.DeclaringANestedDelegateType.cs b/src/Chapter13/Listing13.06.DeclaringANestedDelegateType.cs index 5062bfb3f..6298362af 100644 --- a/src/Chapter13/Listing13.06.DeclaringANestedDelegateType.cs +++ b/src/Chapter13/Listing13.06.DeclaringANestedDelegateType.cs @@ -1,10 +1,9 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_06; + +#region INCLUDE +public class DelegateSample { - #region INCLUDE - public class DelegateSample - { - public delegate bool ComparisonHandler( - int first, int second); - } - #endregion INCLUDE -} \ No newline at end of file + public delegate bool ComparisonHandler( + int first, int second); +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.07.DeclaringAFuncCompatibleMethod.cs b/src/Chapter13/Listing13.07.DeclaringAFuncCompatibleMethod.cs index 0ab6a79dd..c1a88ef65 100644 --- a/src/Chapter13/Listing13.07.DeclaringAFuncCompatibleMethod.cs +++ b/src/Chapter13/Listing13.07.DeclaringAFuncCompatibleMethod.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_07; + +using System; +#region INCLUDE +public class DelegateSample { - using System; - #region INCLUDE - public class DelegateSample + public static void BubbleSort( + int[] items, Func compare) + #region EXCLUDE { - public static void BubbleSort( - int[] items, Func compare) - #region EXCLUDE - { - int i; - int j; - int temp; + int i; + int j; + int temp; - if(items == null) - { - return; - } - if(compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } + if(items == null) + { + return; + } + if(compare == null) + { + throw new ArgumentNullException(nameof(compare)); + } - for(i = items.Length - 1; i >= 0; i--) + for(i = items.Length - 1; i >= 0; i--) + { + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(compare(items[j - 1], items[j])) { - if(compare(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } - #endregion EXCLUDE - #region HIGHLIGHT - public static bool GreaterThan(int first, int second) - { - return first > second; - } - #endregion HIGHLIGHT - - // ... } - #endregion INCLUDE -} \ No newline at end of file + #endregion EXCLUDE + #region HIGHLIGHT + public static bool GreaterThan(int first, int second) + { + return first > second; + } + #endregion HIGHLIGHT + + // ... +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.08.UsingMethodNameAsArgument.cs b/src/Chapter13/Listing13.08.UsingMethodNameAsArgument.cs index 7b05c9760..6822502de 100644 --- a/src/Chapter13/Listing13.08.UsingMethodNameAsArgument.cs +++ b/src/Chapter13/Listing13.08.UsingMethodNameAsArgument.cs @@ -1,71 +1,70 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_08; + +using System; +#region INCLUDE +public class DelegateSample { - using System; - #region INCLUDE - public class DelegateSample + public static void BubbleSort( + int[] items, Func compare) + #region EXCLUDE { - public static void BubbleSort( - int[] items, Func compare) - #region EXCLUDE - { - int i; - int j; - int temp; - - if(items == null) - { - return; - } - if(compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } + int i; + int j; + int temp; - for(i = items.Length - 1; i >= 0; i--) - { - for(j = 1; j <= i; j++) - { - if(compare(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } - } - } + if(items == null) + { + return; } - #endregion EXCLUDE - #region HIGHLIGHT - public static bool GreaterThan(int first, int second) - #endregion HIGHLIGHT + if(compare == null) { - return first > second; + throw new ArgumentNullException(nameof(compare)); } - public static void Main() + for(i = items.Length - 1; i >= 0; i--) { - int[] items = new int[5]; - - for(int i = 0; i < items.Length; i++) + for(j = 1; j <= i; j++) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) + if(compare(items[j - 1], items[j])) { - Console.WriteLine($"'{text}' is not a valid integer."); - return; + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } + } + } + #endregion EXCLUDE + #region HIGHLIGHT + public static bool GreaterThan(int first, int second) + #endregion HIGHLIGHT + { + return first > second; + } - #region HIGHLIGHT - BubbleSort(items, GreaterThan); - #endregion HIGHLIGHT + public static void Main() + { + int[] items = new int[5]; - for (int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.WriteLine(items[i]); + Console.WriteLine($"'{text}' is not a valid integer."); + return; } } + + #region HIGHLIGHT + BubbleSort(items, GreaterThan); + #endregion HIGHLIGHT + + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); + } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.09.PassingADelegateAsAParameterInCSharp.cs b/src/Chapter13/Listing13.09.PassingADelegateAsAParameterInCSharp.cs index 57432ad75..897edd911 100644 --- a/src/Chapter13/Listing13.09.PassingADelegateAsAParameterInCSharp.cs +++ b/src/Chapter13/Listing13.09.PassingADelegateAsAParameterInCSharp.cs @@ -1,63 +1,62 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_09 -{ - using System; - using Listing13_05; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_09; + +using System; +using Listing13_05; - public class DelegateSample +public class DelegateSample +{ + public static void BubbleSort( + int[] items, Comparer compare) { - public static void BubbleSort( - int[] items, Comparer compare) - { - int i; - int j; - int temp; + int i; + int j; + int temp; - if(items == null) - { - return; - } - if(compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } + if(items == null) + { + return; + } + if(compare == null) + { + throw new ArgumentNullException(nameof(compare)); + } - for(i = items.Length - 1; i >= 0; i--) + for(i = items.Length - 1; i >= 0; i--) + { + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(compare(items[j - 1], items[j])) { - if(compare(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } + } + + public static bool GreaterThan(int first, int second) + { + return first > second; + } + + public static void Main() + { + int i; + int[] items = new int[100]; + Random random = new Random(); - public static bool GreaterThan(int first, int second) + for(i = 0; i < items.Length; i++) { - return first > second; + items[i] = random.Next(int.MinValue, int.MaxValue); } - - public static void Main() + #region INCLUDE + BubbleSort(items, + new Comparer(GreaterThan)); + #endregion INCLUDE + for (i = 0; i < items.Length; i++) { - int i; - int[] items = new int[100]; - Random random = new Random(); - - for(i = 0; i < items.Length; i++) - { - items[i] = random.Next(int.MinValue, int.MaxValue); - } - #region INCLUDE - BubbleSort(items, - new Comparer(GreaterThan)); - #endregion INCLUDE - for (i = 0; i < items.Length; i++) - { - Console.WriteLine(items[i]); - } + Console.WriteLine(items[i]); } } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.10.SystemDelegateCannotBeBaseClass.cs b/src/Chapter13/Listing13.10.SystemDelegateCannotBeBaseClass.cs index 56ad045b5..19f455114 100644 --- a/src/Chapter13/Listing13.10.SystemDelegateCannotBeBaseClass.cs +++ b/src/Chapter13/Listing13.10.SystemDelegateCannotBeBaseClass.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_10; + +/* +#region INCLUDE +// ERROR: Func cannot +// inherit from special class 'System.Delegate' +public class Func: System.Delegate { - /* - #region INCLUDE - // ERROR: Func cannot - // inherit from special class 'System.Delegate' - public class Func: System.Delegate - { - // ... - } - #endregion INCLUDE - */ -} \ No newline at end of file +// ... +} +#endregion INCLUDE +*/ \ No newline at end of file diff --git a/src/Chapter13/Listing13.11.UsingADifferentFuncCompatibleMethod.cs b/src/Chapter13/Listing13.11.UsingADifferentFuncCompatibleMethod.cs index 8ec2fcb7a..88c53871c 100644 --- a/src/Chapter13/Listing13.11.UsingADifferentFuncCompatibleMethod.cs +++ b/src/Chapter13/Listing13.11.UsingADifferentFuncCompatibleMethod.cs @@ -1,72 +1,71 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_11 -{ - #region INCLUDE - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_11; + +#region INCLUDE +using System; - public class DelegateSample +public class DelegateSample +{ + public static void BubbleSort( + int[] items, Func compare) { - public static void BubbleSort( - int[] items, Func compare) - { - int i; - int j; - int temp; + int i; + int j; + int temp; - for(i = items.Length - 1; i >= 0; i--) + for(i = items.Length - 1; i >= 0; i--) + { + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(compare(items[j - 1], items[j])) { - if(compare(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } + } - public static bool GreaterThan(int first, int second) - { - return first > second; - } + public static bool GreaterThan(int first, int second) + { + return first > second; + } - #region HIGHLIGHT - public static bool AlphabeticalGreaterThan( - int first, int second) - { - int comparison; - comparison = (first.ToString().CompareTo( - second.ToString())); + #region HIGHLIGHT + public static bool AlphabeticalGreaterThan( + int first, int second) + { + int comparison; + comparison = (first.ToString().CompareTo( + second.ToString())); - return comparison > 0; - } - #endregion HIGHLIGHT + return comparison > 0; + } + #endregion HIGHLIGHT - public static void Main() - { - int[] items = new int[5]; + public static void Main() + { + int[] items = new int[5]; - for(int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } + } - #region HIGHLIGHT - BubbleSort(items, AlphabeticalGreaterThan); - #endregion HIGHLIGHT + #region HIGHLIGHT + BubbleSort(items, AlphabeticalGreaterThan); + #endregion HIGHLIGHT - for (int i = 0; i < items.Length; i++) - { - Console.WriteLine(items[i]); - } + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.12.CreatingDelegateWithStatementLambda.cs b/src/Chapter13/Listing13.12.CreatingDelegateWithStatementLambda.cs index ec2d71530..b57e93298 100644 --- a/src/Chapter13/Listing13.12.CreatingDelegateWithStatementLambda.cs +++ b/src/Chapter13/Listing13.12.CreatingDelegateWithStatementLambda.cs @@ -1,80 +1,79 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_12; + +using System; + +public class DelegateSample { - using System; + public delegate bool ComparisonHandler(int first, int second); - public class DelegateSample + public static void BubbleSort( + int[] items, ComparisonHandler comparisonMethod) { - public delegate bool ComparisonHandler(int first, int second); + int i; + int j; + int temp; - public static void BubbleSort( - int[] items, ComparisonHandler comparisonMethod) + for(i = items.Length - 1; i >= 0; i--) { - int i; - int j; - int temp; - - for(i = items.Length - 1; i >= 0; i--) + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(comparisonMethod(items[j - 1], items[j])) { - if(comparisonMethod(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } + } - public static bool GreaterThan(int first, int second) - { - return first > second; - } + public static bool GreaterThan(int first, int second) + { + return first > second; + } - // New method - public static bool AlphabeticalGreaterThan( - int first, int second) - { - int comparison; - comparison = (first.ToString().CompareTo( - second.ToString())); + // New method + public static bool AlphabeticalGreaterThan( + int first, int second) + { + int comparison; + comparison = (first.ToString().CompareTo( + second.ToString())); - return comparison > 0; - } + return comparison > 0; + } - public static void Main() - { - int[] items = new int[5]; + public static void Main() + { + int[] items = new int[5]; - for(int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } - #region INCLUDE - //... - - #region HIGHLIGHT - BubbleSort(items, - (int first, int second) => - { - return first < second; - } - ); - #endregion HIGHLIGHT + } + #region INCLUDE + //... - //... - #endregion INCLUDE - for (int i = 0; i < items.Length; i++) + #region HIGHLIGHT + BubbleSort(items, + (int first, int second) => { - Console.WriteLine(items[i]); + return first < second; } + ); + #endregion HIGHLIGHT + + //... + #endregion INCLUDE + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.13.OmittingParameterTypesFromStatementLambdas.cs b/src/Chapter13/Listing13.13.OmittingParameterTypesFromStatementLambdas.cs index 3f58e9b0c..7d3d21d2c 100644 --- a/src/Chapter13/Listing13.13.OmittingParameterTypesFromStatementLambdas.cs +++ b/src/Chapter13/Listing13.13.OmittingParameterTypesFromStatementLambdas.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_13; + +using System; +using Listing13_11; +public class Program { - using System; - using Listing13_11; - public class Program + public static void Main() { - public static void Main() - { - int[] items = new int[5]; + int[] items = new int[5]; - for(int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } - #region INCLUDE - //... - DelegateSample.BubbleSort(items, - (first, second) => - { - return first < second; - } - ); - //... - #endregion INCLUDE - - for (int i = 0; i < items.Length; i++) + } + #region INCLUDE + //... + DelegateSample.BubbleSort(items, + (first, second) => { - Console.WriteLine(items[i]); + return first < second; } + ); + //... + #endregion INCLUDE + + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.14.StatementLambdasWithASingleInputParameter.cs b/src/Chapter13/Listing13.14.StatementLambdasWithASingleInputParameter.cs index ffe07ecaa..8ce0a7b92 100644 --- a/src/Chapter13/Listing13.14.StatementLambdasWithASingleInputParameter.cs +++ b/src/Chapter13/Listing13.14.StatementLambdasWithASingleInputParameter.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_14 -{ - #region INCLUDE - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_14; + +#region INCLUDE +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; - #region EXCLUDE - public class Program +#region EXCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - IEnumerable processes = Process.GetProcesses().Where( - process => { return process.WorkingSet64 > 1000000000; }); - // ... - #endregion INCLUDE - } +#endregion EXCLUDE + IEnumerable processes = Process.GetProcesses().Where( + process => { return process.WorkingSet64 > 1000000000; }); + // ... +#endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.15.ParameterlessStatementLambdas.cs b/src/Chapter13/Listing13.15.ParameterlessStatementLambdas.cs index 2334659fa..1cf72e303 100644 --- a/src/Chapter13/Listing13.15.ParameterlessStatementLambdas.cs +++ b/src/Chapter13/Listing13.15.ParameterlessStatementLambdas.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_15; + +using System; +public class Program { - using System; - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - //... - Func getUserInput = - #region HIGHLIGHT - () => - #endregion HIGHLIGHT + #region INCLUDE + //... + Func getUserInput = + #region HIGHLIGHT + () => + #endregion HIGHLIGHT + { + string? input; + do { - string? input; - do - { - input = Console.ReadLine(); - } - while(!string.IsNullOrWhiteSpace(input)); - return input!; - }; - //... - #endregion INCLUDE - getUserInput(); - } + input = Console.ReadLine(); + } + while(!string.IsNullOrWhiteSpace(input)); + return input!; + }; + //... + #endregion INCLUDE + getUserInput(); } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.16.PassingADelegateWithAnExpressionLambda.cs b/src/Chapter13/Listing13.16.PassingADelegateWithAnExpressionLambda.cs index 3f90b6e13..6fd7c7f71 100644 --- a/src/Chapter13/Listing13.16.PassingADelegateWithAnExpressionLambda.cs +++ b/src/Chapter13/Listing13.16.PassingADelegateWithAnExpressionLambda.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_16; + +using System; +using Listing13_11; +public class Program { - using System; - using Listing13_11; - public class Program + public static void Main() { - public static void Main() - { - int[] items = new int[5]; + int[] items = new int[5]; - for (int i = 0; i < items.Length; i++) + for (int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } - #region INCLUDE - //... - #region HIGHLIGHT - DelegateSample.BubbleSort - (items, (first, second) => first < second); - #endregion HIGHLIGHT - //... - #endregion INCLUDE + } + #region INCLUDE + //... + #region HIGHLIGHT + DelegateSample.BubbleSort + (items, (first, second) => first < second); + #endregion HIGHLIGHT + //... + #endregion INCLUDE - for (int i = 0; i < items.Length; i++) - { - Console.WriteLine(items[i]); - } + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.17.PassingAnAnonymousMethodInCSharpTwo.cs b/src/Chapter13/Listing13.17.PassingAnAnonymousMethodInCSharpTwo.cs index 0dd693cc1..80ab3050e 100644 --- a/src/Chapter13/Listing13.17.PassingAnAnonymousMethodInCSharpTwo.cs +++ b/src/Chapter13/Listing13.17.PassingAnAnonymousMethodInCSharpTwo.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_17; + +using System; +using Listing13_11; +public class Program { - using System; - using Listing13_11; - public class Program + public static void Main() { - public static void Main() - { - int[] items = new int[5]; + int[] items = new int[5]; - for(int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } - #region INCLUDE - //... - DelegateSample.BubbleSort(items, - delegate(int first, int second) - { - return first < second; - } - ); - //... - #endregion INCLUDE - - for (int i = 0; i < items.Length; i++) + } + #region INCLUDE + //... + DelegateSample.BubbleSort(items, + delegate(int first, int second) { - Console.WriteLine(items[i]); + return first < second; } + ); + //... + #endregion INCLUDE + + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.18.UsingVarianceForDelegates.cs b/src/Chapter13/Listing13.18.UsingVarianceForDelegates.cs index 4aa4d653e..c24bdfb31 100644 --- a/src/Chapter13/Listing13.18.UsingVarianceForDelegates.cs +++ b/src/Chapter13/Listing13.18.UsingVarianceForDelegates.cs @@ -1,34 +1,33 @@ // Justification: Left as lamda to elucidate generic types. #pragma warning disable IDE0039 // Use local function -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_18 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_18; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - // Contravariance - Action broadAction = - (object data) => - { - Console.WriteLine(data); - }; + #region INCLUDE + // Contravariance + Action broadAction = + (object data) => + { + Console.WriteLine(data); + }; - Action narrowAction = broadAction; + Action narrowAction = broadAction; - // Covariance - Func narrowFunction = - () => Console.ReadLine(); - Func broadFunction = narrowFunction; + // Covariance + Func narrowFunction = + () => Console.ReadLine(); + Func broadFunction = narrowFunction; - // Contravariance and covariance combined - Func func1 = - (object data) => data.ToString(); + // Contravariance and covariance combined + Func func1 = + (object data) => data.ToString(); - Func func2 = func1; - #endregion INCLUDE - } + Func func2 = func1; + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter13/Listing13.19.CSharpEquivalentOfCILGeneratedByTheCompilerForLambdaExpressions.cs b/src/Chapter13/Listing13.19.CSharpEquivalentOfCILGeneratedByTheCompilerForLambdaExpressions.cs index b273aa0b4..2fa551200 100644 --- a/src/Chapter13/Listing13.19.CSharpEquivalentOfCILGeneratedByTheCompilerForLambdaExpressions.cs +++ b/src/Chapter13/Listing13.19.CSharpEquivalentOfCILGeneratedByTheCompilerForLambdaExpressions.cs @@ -1,68 +1,67 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_19; + +using System; +#region INCLUDE +public class DelegateSample { - using System; - #region INCLUDE - public class DelegateSample + #region EXCLUDE + public delegate bool ComparisonHandler(int first, int second); + + public static void BubbleSort( + int[] items, ComparisonHandler comparisonMethod) { - #region EXCLUDE - public delegate bool ComparisonHandler(int first, int second); + int i; + int j; + int temp; - public static void BubbleSort( - int[] items, ComparisonHandler comparisonMethod) + for(i = items.Length - 1; i >= 0; i--) { - int i; - int j; - int temp; - - for(i = items.Length - 1; i >= 0; i--) + for(j = 1; j <= i; j++) { - for(j = 1; j <= i; j++) + if(comparisonMethod(items[j - 1], items[j])) { - if(comparisonMethod(items[j - 1], items[j])) - { - temp = items[j - 1]; - items[j - 1] = items[j]; - items[j] = temp; - } + temp = items[j - 1]; + items[j - 1] = items[j]; + items[j] = temp; } } } - #endregion EXCLUDE + } + #endregion EXCLUDE - public static void Main() - { - int[] items = new int[5]; + public static void Main() + { + int[] items = new int[5]; - for(int i = 0; i < items.Length; i++) + for(int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } + } - #region HIGHLIGHT - BubbleSort(items, - __AnonymousMethod_00000000); - #endregion HIGHLIGHT - + #region HIGHLIGHT + BubbleSort(items, + __AnonymousMethod_00000000); + #endregion HIGHLIGHT - for (int i = 0; i < items.Length; i++) - { - Console.WriteLine(items[i]); - } - } - #region HIGHLIGHT - private static bool __AnonymousMethod_00000000( - int first, int second) + for (int i = 0; i < items.Length; i++) { - return first < second; + Console.WriteLine(items[i]); } - #endregion HIGHLIGHT + + } + #region HIGHLIGHT + private static bool __AnonymousMethod_00000000( + int first, int second) + { + return first < second; } - #endregion INCLUDE -} \ No newline at end of file + #endregion HIGHLIGHT +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.20.UsingAnOuterVariableInALambdaExpression.cs b/src/Chapter13/Listing13.20.UsingAnOuterVariableInALambdaExpression.cs index e5177819f..568ebc7ac 100644 --- a/src/Chapter13/Listing13.20.UsingAnOuterVariableInALambdaExpression.cs +++ b/src/Chapter13/Listing13.20.UsingAnOuterVariableInALambdaExpression.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_20; + +using System; +using Listing13_11; +#region INCLUDE +public class Program { - using System; - using Listing13_11; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - int[] items = new int[5]; - #region HIGHLIGHT - int comparisonCount = 0; - #endregion HIGHLIGHT + int[] items = new int[5]; + #region HIGHLIGHT + int comparisonCount = 0; + #endregion HIGHLIGHT - for (int i = 0; i < items.Length; i++) + for (int i = 0; i < items.Length; i++) + { + Console.Write("Enter an integer:"); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer:"); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } + Console.WriteLine($"'{text}' is not a valid integer."); + return; } + } - #region HIGHLIGHT - DelegateSample.BubbleSort(items, - (int first, int second) => - { - comparisonCount++; - return first < second; - } - ); - #endregion HIGHLIGHT - - for (int i = 0; i < items.Length; i++) + #region HIGHLIGHT + DelegateSample.BubbleSort(items, + (int first, int second) => { - Console.WriteLine(items[i]); + comparisonCount++; + return first < second; } + ); + #endregion HIGHLIGHT - #region HIGHLIGHT - Console.WriteLine("Items were compared {0} times.", - comparisonCount); - #endregion HIGHLIGHT + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } + + #region HIGHLIGHT + Console.WriteLine("Items were compared {0} times.", + comparisonCount); + #endregion HIGHLIGHT } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.21.CSharpEquivalentOfCILCodeGeneratedByCompilerForOuterVariables.cs b/src/Chapter13/Listing13.21.CSharpEquivalentOfCILCodeGeneratedByCompilerForOuterVariables.cs index 5c9454010..5e25db72c 100644 --- a/src/Chapter13/Listing13.21.CSharpEquivalentOfCILCodeGeneratedByCompilerForOuterVariables.cs +++ b/src/Chapter13/Listing13.21.CSharpEquivalentOfCILCodeGeneratedByCompilerForOuterVariables.cs @@ -1,58 +1,57 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_21; + +using System; +using Listing13_11; +#region INCLUDE +public class Program { - using System; - using Listing13_11; - #region INCLUDE - public class Program + // ... + #region HIGHLIGHT + private sealed class __LocalsDisplayClass_00000001 { - // ... - #region HIGHLIGHT - private sealed class __LocalsDisplayClass_00000001 + public int comparisonCount; + public bool __AnonymousMethod_00000000( + int first, int second) { - public int comparisonCount; - public bool __AnonymousMethod_00000000( - int first, int second) - { - comparisonCount++; - return first < second; - } + comparisonCount++; + return first < second; } + } + #endregion HIGHLIGHT + + public static void Main() + { + #region HIGHLIGHT + __LocalsDisplayClass_00000001 locals = + new __LocalsDisplayClass_00000001(); + locals.comparisonCount = 0; #endregion HIGHLIGHT + int[] items = new int[5]; - public static void Main() + for (int i = 0; i < items.Length; i++) { - #region HIGHLIGHT - __LocalsDisplayClass_00000001 locals = - new __LocalsDisplayClass_00000001(); - locals.comparisonCount = 0; - #endregion HIGHLIGHT - int[] items = new int[5]; - - for (int i = 0; i < items.Length; i++) + Console.Write("Enter an integer: "); + string? text = Console.ReadLine(); + if (!int.TryParse(text, out items[i])) { - Console.Write("Enter an integer: "); - string? text = Console.ReadLine(); - if (!int.TryParse(text, out items[i])) - { - Console.WriteLine($"'{text}' is not a valid integer."); - return; - } - } - - #region HIGHLIGHT - DelegateSample.BubbleSort - (items, locals.__AnonymousMethod_00000000); - #endregion HIGHLIGHT - for (int i = 0; i < items.Length; i++) - { - Console.WriteLine(items[i]); + Console.WriteLine($"'{text}' is not a valid integer."); + return; } + } - #region HIGHLIGHT - Console.WriteLine("Items were compared {0} times.", - locals.comparisonCount); - #endregion HIGHLIGHT + #region HIGHLIGHT + DelegateSample.BubbleSort + (items, locals.__AnonymousMethod_00000000); + #endregion HIGHLIGHT + for (int i = 0; i < items.Length; i++) + { + Console.WriteLine(items[i]); } + + #region HIGHLIGHT + Console.WriteLine("Items were compared {0} times.", + locals.comparisonCount); + #endregion HIGHLIGHT } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.22.CapturingLoopVariablesCSharpFive.cs b/src/Chapter13/Listing13.22.CapturingLoopVariablesCSharpFive.cs index 104903d9a..e92297fc7 100644 --- a/src/Chapter13/Listing13.22.CapturingLoopVariablesCSharpFive.cs +++ b/src/Chapter13/Listing13.22.CapturingLoopVariablesCSharpFive.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_22; + +using System; +using System.Collections.Generic; +#region INCLUDE +public class CaptureLoop { - using System; - using System.Collections.Generic; - #region INCLUDE - public class CaptureLoop + public static void Main() { - public static void Main() + var items = new string[] { "Moe", "Larry", "Curly" }; + var actions = new List(); + foreach(string item in items) { - var items = new string[] { "Moe", "Larry", "Curly" }; - var actions = new List(); - foreach(string item in items) - { - actions.Add(() => { Console.WriteLine(item); }); - } - foreach(Action action in actions) - { - action(); - } + actions.Add(() => { Console.WriteLine(item); }); + } + foreach(Action action in actions) + { + action(); } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.23.LoopVariableWorkaroundBeforeCSharpFive.cs b/src/Chapter13/Listing13.23.LoopVariableWorkaroundBeforeCSharpFive.cs index aa4ec795e..d26f027eb 100644 --- a/src/Chapter13/Listing13.23.LoopVariableWorkaroundBeforeCSharpFive.cs +++ b/src/Chapter13/Listing13.23.LoopVariableWorkaroundBeforeCSharpFive.cs @@ -1,27 +1,26 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_23; + +using System; +using System.Collections.Generic; +#region INCLUDE +public class DoNotCaptureLoop { - using System; - using System.Collections.Generic; - #region INCLUDE - public class DoNotCaptureLoop + public static void Main() { - public static void Main() + var items = new string[] { "Moe", "Larry", "Curly" }; + var actions = new List(); + foreach(string item in items) { - var items = new string[] { "Moe", "Larry", "Curly" }; - var actions = new List(); - foreach(string item in items) - { - #region HIGHLIGHT - string _item = item; - #endregion HIGHLIGHT - actions.Add( - () => { Console.WriteLine(_item); }); - } - foreach(Action action in actions) - { - action(); - } + #region HIGHLIGHT + string _item = item; + #endregion HIGHLIGHT + actions.Add( + () => { Console.WriteLine(_item); }); + } + foreach(Action action in actions) + { + action(); } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter13/Listing13.24.ConvertingExpressionTreeToSqlWhereClause.cs b/src/Chapter13/Listing13.24.ConvertingExpressionTreeToSqlWhereClause.cs index 74aaeb37a..fe5a4d399 100644 --- a/src/Chapter13/Listing13.24.ConvertingExpressionTreeToSqlWhereClause.cs +++ b/src/Chapter13/Listing13.24.ConvertingExpressionTreeToSqlWhereClause.cs @@ -1,12 +1,11 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_24 -{ - /* - #region INCLUDE - EXPRESSION TREE: - persons.Where(person => person.Name.ToUpper() == "INIGO MONTOYA"); - - SQL WHERE CLAUSE: - select * from Person where upper(Name) = 'INIGO MONTOYA'; - #endregion INCLUDE - */ -} \ No newline at end of file +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_24; + +/* +#region INCLUDE +EXPRESSION TREE: + persons.Where(person => person.Name.ToUpper() == "INIGO MONTOYA"); + +SQL WHERE CLAUSE: + select * from Person where upper(Name) = 'INIGO MONTOYA'; +#endregion INCLUDE + */ \ No newline at end of file diff --git a/src/Chapter13/Listing13.25.ExamingingAnExpressionTree.cs b/src/Chapter13/Listing13.25.ExamingingAnExpressionTree.cs index 9046651ea..0536d1a27 100644 --- a/src/Chapter13/Listing13.25.ExamingingAnExpressionTree.cs +++ b/src/Chapter13/Listing13.25.ExamingingAnExpressionTree.cs @@ -1,62 +1,61 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_25 -{ - #region INCLUDE - using System; - using System.Linq.Expressions; - using static System.Linq.Expressions.ExpressionType; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter13.Listing13_25; - public class Program - { - public static void Main() - { - Expression> expression; - expression = (x, y) => x > y; - Console.WriteLine("------------- {0} -------------", - expression); - PrintNode(expression.Body, 0); - Console.WriteLine(); - Console.WriteLine(); - expression = (x, y) => x * y > x + y; - Console.WriteLine("------------- {0} -------------", - expression); - PrintNode(expression.Body, 0); - } +#region INCLUDE +using System; +using System.Linq.Expressions; +using static System.Linq.Expressions.ExpressionType; - public static void PrintNode(Expression expression, - int indent) - { - if (expression is BinaryExpression binaryExpression) - PrintNode(binaryExpression, indent); - else - PrintSingle(expression, indent); - } +public class Program +{ + public static void Main() + { + Expression> expression; + expression = (x, y) => x > y; + Console.WriteLine("------------- {0} -------------", + expression); + PrintNode(expression.Body, 0); + Console.WriteLine(); + Console.WriteLine(); + expression = (x, y) => x * y > x + y; + Console.WriteLine("------------- {0} -------------", + expression); + PrintNode(expression.Body, 0); + } - private static void PrintNode(BinaryExpression expression, - int indent) - { - PrintNode(expression.Left, indent + 1); + public static void PrintNode(Expression expression, + int indent) + { + if (expression is BinaryExpression binaryExpression) + PrintNode(binaryExpression, indent); + else PrintSingle(expression, indent); - PrintNode(expression.Right, indent + 1); - } - - private static void PrintSingle( - Expression expression, int indent) => - Console.WriteLine("{0," + indent * 5 + "}{1}", - "", NodeToString(expression)); + } - private static string NodeToString(Expression expression) => - expression.NodeType switch - { - // using static ExpressionType - Multiply => "*", - Add => "+", - Divide => "/", - Subtract => "-", - GreaterThan => ">", - LessThan => "<", - _ => expression.ToString() + - " (" + expression.NodeType.ToString() + ")", - }; - #endregion INCLUDE + private static void PrintNode(BinaryExpression expression, + int indent) + { + PrintNode(expression.Left, indent + 1); + PrintSingle(expression, indent); + PrintNode(expression.Right, indent + 1); } + + private static void PrintSingle( + Expression expression, int indent) => + Console.WriteLine("{0," + indent * 5 + "}{1}", + "", NodeToString(expression)); + + private static string NodeToString(Expression expression) => + expression.NodeType switch + { + // using static ExpressionType + Multiply => "*", + Add => "+", + Divide => "/", + Subtract => "-", + GreaterThan => ">", + LessThan => "<", + _ => expression.ToString() + + " (" + expression.NodeType.ToString() + ")", + }; + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter14/Listing14.01.HeaterAndCoolerEventSubscriberImplementations.cs b/src/Chapter14/Listing14.01.HeaterAndCoolerEventSubscriberImplementations.cs index c0297b914..bdb0277a2 100644 --- a/src/Chapter14/Listing14.01.HeaterAndCoolerEventSubscriberImplementations.cs +++ b/src/Chapter14/Listing14.01.HeaterAndCoolerEventSubscriberImplementations.cs @@ -1,54 +1,53 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_01; + +#region INCLUDE +public class Cooler { - #region INCLUDE - public class Cooler + public Cooler(float temperature) { - public Cooler(float temperature) - { - Temperature = temperature; - } + Temperature = temperature; + } - // Cooler is activated when ambient temperature - // is higher than this - public float Temperature { get; set; } + // Cooler is activated when ambient temperature + // is higher than this + public float Temperature { get; set; } - // Notifies that the temperature changed on this instance - public void OnTemperatureChanged(float newTemperature) + // Notifies that the temperature changed on this instance + public void OnTemperatureChanged(float newTemperature) + { + if(newTemperature > Temperature) + { + System.Console.WriteLine("Cooler: On"); + } + else { - if(newTemperature > Temperature) - { - System.Console.WriteLine("Cooler: On"); - } - else - { - System.Console.WriteLine("Cooler: Off"); - } + System.Console.WriteLine("Cooler: Off"); } } +} - public class Heater +public class Heater +{ + public Heater(float temperature) { - public Heater(float temperature) - { - Temperature = temperature; - } + Temperature = temperature; + } - // Heater is activated when ambient temperature - // is lower than this - public float Temperature { get; set; } + // Heater is activated when ambient temperature + // is lower than this + public float Temperature { get; set; } - // Notifies that the temperature changed on this instance - public void OnTemperatureChanged(float newTemperature) + // Notifies that the temperature changed on this instance + public void OnTemperatureChanged(float newTemperature) + { + if(newTemperature < Temperature) + { + System.Console.WriteLine("Heater: On"); + } + else { - if(newTemperature < Temperature) - { - System.Console.WriteLine("Heater: On"); - } - else - { - System.Console.WriteLine("Heater: Off"); - } + System.Console.WriteLine("Heater: Off"); } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.02.DefiningTheEventPublsherThermostat.cs b/src/Chapter14/Listing14.02.DefiningTheEventPublsherThermostat.cs index b308d3ed2..614d85997 100644 --- a/src/Chapter14/Listing14.02.DefiningTheEventPublsherThermostat.cs +++ b/src/Chapter14/Listing14.02.DefiningTheEventPublsherThermostat.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_02; + +using System; +#region INCLUDE +public class Thermostat { - using System; - #region INCLUDE - public class Thermostat - { - // Define the event publisher (initially without the sender) - public Action? OnTemperatureChange { get; set; } + // Define the event publisher (initially without the sender) + public Action? OnTemperatureChange { get; set; } - public float CurrentTemperature { get; set; } - #endregion INCLUDE - } + public float CurrentTemperature { get; set; } + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter14/Listing14.03.ConnectingThePublisherAndSubscribers.cs b/src/Chapter14/Listing14.03.ConnectingThePublisherAndSubscribers.cs index 48c45e686..f3d303c68 100644 --- a/src/Chapter14/Listing14.03.ConnectingThePublisherAndSubscribers.cs +++ b/src/Chapter14/Listing14.03.ConnectingThePublisherAndSubscribers.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_03; + +using System; +using Listing14_01; +using Listing14_02; +#region INCLUDE +public class Program { - using System; - using Listing14_01; - using Listing14_02; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - #region HIGHLIGHT - thermostat.OnTemperatureChange += - heater.OnTemperatureChanged; - thermostat.OnTemperatureChange += - cooler.OnTemperatureChanged; - #endregion HIGHLIGHT + #region HIGHLIGHT + thermostat.OnTemperatureChange += + heater.OnTemperatureChanged; + thermostat.OnTemperatureChange += + cooler.OnTemperatureChanged; + #endregion HIGHLIGHT - Console.Write("Enter temperature: "); - string? temperature = Console.ReadLine(); - if (!int.TryParse(temperature, out int currentTemperature)) - { - Console.WriteLine($"'{temperature}' is not a valid integer."); - return; - } - thermostat.CurrentTemperature = currentTemperature; + Console.Write("Enter temperature: "); + string? temperature = Console.ReadLine(); + if (!int.TryParse(temperature, out int currentTemperature)) + { + Console.WriteLine($"'{temperature}' is not a valid integer."); + return; } + thermostat.CurrentTemperature = currentTemperature; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.04.ConnectingThePublisherAndSubscribers.Placeholder.cs b/src/Chapter14/Listing14.04.ConnectingThePublisherAndSubscribers.Placeholder.cs index fceaaf0e6..683210ec3 100644 --- a/src/Chapter14/Listing14.04.ConnectingThePublisherAndSubscribers.Placeholder.cs +++ b/src/Chapter14/Listing14.04.ConnectingThePublisherAndSubscribers.Placeholder.cs @@ -1,29 +1,28 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_04 -{ - using System; - using Listing14_01; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_04; + +using System; +using Listing14_01; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - thermostat.OnTemperatureChange += - heater.OnTemperatureChanged; - thermostat.OnTemperatureChange += - cooler.OnTemperatureChanged; + thermostat.OnTemperatureChange += + heater.OnTemperatureChanged; + thermostat.OnTemperatureChange += + cooler.OnTemperatureChanged; - Console.Write("Enter temperature: "); - string? temperature = Console.ReadLine(); - if (!int.TryParse(temperature, out int currentTemperature)) - { - Console.WriteLine($"'{temperature}' is not a valid integer."); - return; - } - thermostat.CurrentTemperature = currentTemperature; + Console.Write("Enter temperature: "); + string? temperature = Console.ReadLine(); + if (!int.TryParse(temperature, out int currentTemperature)) + { + Console.WriteLine($"'{temperature}' is not a valid integer."); + return; } + thermostat.CurrentTemperature = currentTemperature; } } \ No newline at end of file diff --git a/src/Chapter14/Listing14.04.InvokingADelegateWithoutCheckingForNull.cs b/src/Chapter14/Listing14.04.InvokingADelegateWithoutCheckingForNull.cs index a4be893fd..62e209da7 100644 --- a/src/Chapter14/Listing14.04.InvokingADelegateWithoutCheckingForNull.cs +++ b/src/Chapter14/Listing14.04.InvokingADelegateWithoutCheckingForNull.cs @@ -1,39 +1,38 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_04; + +using System; +#region INCLUDE +public class Thermostat { - using System; - #region INCLUDE - public class Thermostat + #region EXCLUDE + // Define the event publisher + public Action? OnTemperatureChange { get; set; } + #endregion EXCLUDE + public float CurrentTemperature { - #region EXCLUDE - // Define the event publisher - public Action? OnTemperatureChange { get; set; } - #endregion EXCLUDE - public float CurrentTemperature + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + #region HIGHLIGHT + if (value != CurrentTemperature) + #endregion HIGHLIGHT { #region HIGHLIGHT - if (value != CurrentTemperature) + _CurrentTemperature = value; #endregion HIGHLIGHT - { - #region HIGHLIGHT - _CurrentTemperature = value; - #endregion HIGHLIGHT - // Call subscribers - // Incomplete, check for null needed - #region EXCLUDE - #pragma warning disable CS8602 // Dereference of a possibly null reference. - #endregion EXCLUDE - OnTemperatureChange(value); - #region EXCLUDE - #pragma warning restore CS8602 // Dereference of a possibly null reference. - #endregion EXCLUDE - } + // Call subscribers + // Incomplete, check for null needed + #region EXCLUDE + #pragma warning disable CS8602 // Dereference of a possibly null reference. + #endregion EXCLUDE + OnTemperatureChange(value); + #region EXCLUDE + #pragma warning restore CS8602 // Dereference of a possibly null reference. + #endregion EXCLUDE } } - private float _CurrentTemperature; } - #endregion INCLUDE -} \ No newline at end of file + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.05.InvokingADelegate.cs b/src/Chapter14/Listing14.05.InvokingADelegate.cs index 40177c9f8..ed860aea4 100644 --- a/src/Chapter14/Listing14.05.InvokingADelegate.cs +++ b/src/Chapter14/Listing14.05.InvokingADelegate.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_05; + +using System; +#region INCLUDE +public class Thermostat { - using System; - #region INCLUDE - public class Thermostat - { - // Define the event publisher - public Action? OnTemperatureChange { get; set; } + // Define the event publisher + public Action? OnTemperatureChange { get; set; } - public float CurrentTemperature + public float CurrentTemperature + { + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + if(value != CurrentTemperature) { - if(value != CurrentTemperature) - { - _CurrentTemperature = value; - // If there are any subscribers, - // notify them of changes in - // temperature by invoking said subcribers - #region HIGHLIGHT - OnTemperatureChange?.Invoke(value); // C# 6.0 - #endregion HIGHLIGHT - } + _CurrentTemperature = value; + // If there are any subscribers, + // notify them of changes in + // temperature by invoking said subcribers + #region HIGHLIGHT + OnTemperatureChange?.Invoke(value); // C# 6.0 + #endregion HIGHLIGHT } } - - private float _CurrentTemperature; } - #endregion INCLUDE -} \ No newline at end of file + + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.06.InvokingADelegatePre6.cs b/src/Chapter14/Listing14.06.InvokingADelegatePre6.cs index 4b3d0e545..818fe5383 100644 --- a/src/Chapter14/Listing14.06.InvokingADelegatePre6.cs +++ b/src/Chapter14/Listing14.06.InvokingADelegatePre6.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_06; + +using System; +#region INCLUDE +public class Thermostat { - using System; - #region INCLUDE - public class Thermostat - { - // Define the event publisher - public Action? OnTemperatureChange { get; set; } + // Define the event publisher + public Action? OnTemperatureChange { get; set; } - public float CurrentTemperature + public float CurrentTemperature + { + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + if(value != CurrentTemperature) { - if(value != CurrentTemperature) + _CurrentTemperature = value; + // If there are any subscribers, + // notify them of changes in + // temperature + #region EXCLUDE + #pragma warning disable IDE1005 // Delegate invocation can be simplified. + #endregion EXCLUDE + #region HIGHLIGHT + Action? localOnChange = + OnTemperatureChange; + if(localOnChange != null) { - _CurrentTemperature = value; - // If there are any subscribers, - // notify them of changes in - // temperature - #region EXCLUDE - #pragma warning disable IDE1005 // Delegate invocation can be simplified. - #endregion EXCLUDE - #region HIGHLIGHT - Action? localOnChange = - OnTemperatureChange; - if(localOnChange != null) - { - // Call subscribers - localOnChange(value); - } - #endregion HIGHLIGHT - #region EXCLUDE - #pragma warning restore IDE1005 // Delegate invocation can be simplified. - #endregion EXCLUDE + // Call subscribers + localOnChange(value); } + #endregion HIGHLIGHT + #region EXCLUDE + #pragma warning restore IDE1005 // Delegate invocation can be simplified. + #endregion EXCLUDE } } - - private float _CurrentTemperature; } - #endregion INCLUDE -} \ No newline at end of file + + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.07.UsingthePlusEqualsAndMinusEqualsDelegateOperators.cs b/src/Chapter14/Listing14.07.UsingthePlusEqualsAndMinusEqualsDelegateOperators.cs index 248610e16..ba9fbde48 100644 --- a/src/Chapter14/Listing14.07.UsingthePlusEqualsAndMinusEqualsDelegateOperators.cs +++ b/src/Chapter14/Listing14.07.UsingthePlusEqualsAndMinusEqualsDelegateOperators.cs @@ -1,40 +1,39 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_07 -{ - using System; - using Listing14_01; - using Listing14_05; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_07; + +using System; +using Listing14_01; +using Listing14_05; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - //... - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + #region INCLUDE + //... + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - Action delegate1; - Action delegate2; - Action? delegate3; + Action delegate1; + Action delegate2; + Action? delegate3; - delegate1 = heater.OnTemperatureChanged; - delegate2 = cooler.OnTemperatureChanged; + delegate1 = heater.OnTemperatureChanged; + delegate2 = cooler.OnTemperatureChanged; - Console.WriteLine("Invoke both delegates:"); - delegate3 = delegate1; - #region HIGHLIGHT - delegate3 += delegate2; - #endregion HIGHLIGHT - delegate3(90); + Console.WriteLine("Invoke both delegates:"); + delegate3 = delegate1; + #region HIGHLIGHT + delegate3 += delegate2; + #endregion HIGHLIGHT + delegate3(90); - Console.WriteLine("Invoke only delegate2"); - #region HIGHLIGHT - delegate3 -= delegate1; - #endregion HIGHLIGHT - delegate3!(30); - //... - #endregion INCLUDE - } + Console.WriteLine("Invoke only delegate2"); + #region HIGHLIGHT + delegate3 -= delegate1; + #endregion HIGHLIGHT + delegate3!(30); + //... + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter14/Listing14.08.UsingThePlusAndMinusDelegateOperators.cs b/src/Chapter14/Listing14.08.UsingThePlusAndMinusDelegateOperators.cs index 2513370bb..8e1821e1f 100644 --- a/src/Chapter14/Listing14.08.UsingThePlusAndMinusDelegateOperators.cs +++ b/src/Chapter14/Listing14.08.UsingThePlusAndMinusDelegateOperators.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_08; + +using System; +using Listing14_01; +using Listing14_05; +public class Program { - using System; - using Listing14_01; - using Listing14_05; - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - //... - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + #region INCLUDE + //... + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - Action delegate1; - Action delegate2; - Action delegate3; + Action delegate1; + Action delegate2; + Action delegate3; - delegate1 = heater.OnTemperatureChanged; - delegate2 = cooler.OnTemperatureChanged; + delegate1 = heater.OnTemperatureChanged; + delegate2 = cooler.OnTemperatureChanged; - Console.WriteLine("Combine delegates using + operator:"); - #region HIGHLIGHT - delegate3 = delegate1 + delegate2; - #endregion HIGHLIGHT - delegate3(60); + Console.WriteLine("Combine delegates using + operator:"); + #region HIGHLIGHT + delegate3 = delegate1 + delegate2; + #endregion HIGHLIGHT + delegate3(60); - Console.WriteLine("Uncombine delegates using - operator:"); - #region HIGHLIGHT - delegate3 = (delegate3 - delegate2)!; - #endregion HIGHLIGHT - delegate3(60); - //... - #endregion INCLUDE - } + Console.WriteLine("Uncombine delegates using - operator:"); + #region HIGHLIGHT + delegate3 = (delegate3 - delegate2)!; + #endregion HIGHLIGHT + delegate3(60); + //... + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter14/Listing14.09.OnTemperatureChangedThrowingAnException.cs b/src/Chapter14/Listing14.09.OnTemperatureChangedThrowingAnException.cs index 26d076a6e..26c887c25 100644 --- a/src/Chapter14/Listing14.09.OnTemperatureChangedThrowingAnException.cs +++ b/src/Chapter14/Listing14.09.OnTemperatureChangedThrowingAnException.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_09; + +using System; +using Listing14_01; +using Listing14_05; +#region INCLUDE +public class Program { - using System; - using Listing14_01; - using Listing14_05; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - thermostat.OnTemperatureChange += - heater.OnTemperatureChanged; - #region HIGHLIGHT - thermostat.OnTemperatureChange += - (newTemperature) => - { - throw new InvalidOperationException(); - }; - #endregion HIGHLIGHT - thermostat.OnTemperatureChange += - cooler.OnTemperatureChanged; + thermostat.OnTemperatureChange += + heater.OnTemperatureChanged; + #region HIGHLIGHT + thermostat.OnTemperatureChange += + (newTemperature) => + { + throw new InvalidOperationException(); + }; + #endregion HIGHLIGHT + thermostat.OnTemperatureChange += + cooler.OnTemperatureChanged; - Console.Write("Enter temperature: "); - string? temperature = Console.ReadLine(); - if (!int.TryParse(temperature, out int currentTemperature)) - { - Console.WriteLine($"'{temperature}' is not a valid integer."); - return; - } - thermostat.CurrentTemperature = currentTemperature; + Console.Write("Enter temperature: "); + string? temperature = Console.ReadLine(); + if (!int.TryParse(temperature, out int currentTemperature)) + { + Console.WriteLine($"'{temperature}' is not a valid integer."); + return; } + thermostat.CurrentTemperature = currentTemperature; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.10.HandlingExceptionsFromSubscribers.cs b/src/Chapter14/Listing14.10.HandlingExceptionsFromSubscribers.cs index 2af8f6762..261b8f9e2 100644 --- a/src/Chapter14/Listing14.10.HandlingExceptionsFromSubscribers.cs +++ b/src/Chapter14/Listing14.10.HandlingExceptionsFromSubscribers.cs @@ -1,100 +1,99 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_10; + +using System; +using System.Collections.Generic; +using Listing14_01; +#region INCLUDE +public class Thermostat { - using System; - using System.Collections.Generic; - using Listing14_01; - #region INCLUDE - public class Thermostat - { - // Define the event publisher - public Action? OnTemperatureChange; + // Define the event publisher + public Action? OnTemperatureChange; - public float CurrentTemperature + public float CurrentTemperature + { + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + if(value != CurrentTemperature) { - if(value != CurrentTemperature) + _CurrentTemperature = value; + Action? onTemperatureChange + = OnTemperatureChange; + if (onTemperatureChange != null) { - _CurrentTemperature = value; - Action? onTemperatureChange - = OnTemperatureChange; - if (onTemperatureChange != null) + #region HIGHLIGHT + List exceptionCollection = + new List(); + foreach( + Delegate handler in + onTemperatureChange.GetInvocationList()) { - #region HIGHLIGHT - List exceptionCollection = - new List(); - foreach( - Delegate handler in - onTemperatureChange.GetInvocationList()) + try { - try - { - ((Action)handler)(value); - } - catch(Exception exception) - { - exceptionCollection.Add(exception); - } + ((Action)handler)(value); } - if(exceptionCollection.Count > 0) + catch(Exception exception) { - throw new AggregateException( - "There were exceptions thrown by " + - "OnTemperatureChange Event subscribers.", - exceptionCollection); + exceptionCollection.Add(exception); } - #endregion HIGHLIGHT } + if(exceptionCollection.Count > 0) + { + throw new AggregateException( + "There were exceptions thrown by " + + "OnTemperatureChange Event subscribers.", + exceptionCollection); + } + #endregion HIGHLIGHT } } } - private float _CurrentTemperature; } - #endregion INCLUDE + private float _CurrentTemperature; +} +#endregion INCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() + try { - try - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); - - thermostat.OnTemperatureChange += - heater.OnTemperatureChanged; - thermostat.OnTemperatureChange += - (newTemperature) => - { - throw new InvalidOperationException(); - }; - thermostat.OnTemperatureChange += - cooler.OnTemperatureChanged; + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - Console.Write("Enter temperature: "); - string? temperature = Console.ReadLine(); - if (!int.TryParse(temperature, out int currentTemperature)) + thermostat.OnTemperatureChange += + heater.OnTemperatureChanged; + thermostat.OnTemperatureChange += + (newTemperature) => { - Console.WriteLine($"'{temperature}' is not a valid integer."); - return; - } - thermostat.CurrentTemperature = currentTemperature; + throw new InvalidOperationException(); + }; + thermostat.OnTemperatureChange += + cooler.OnTemperatureChanged; + + Console.Write("Enter temperature: "); + string? temperature = Console.ReadLine(); + if (!int.TryParse(temperature, out int currentTemperature)) + { + Console.WriteLine($"'{temperature}' is not a valid integer."); + return; } - catch(AggregateException exception) + thermostat.CurrentTemperature = currentTemperature; + } + catch(AggregateException exception) + { + Console.WriteLine(exception.Message); + if (exception.InnerExceptions.Count < 1) { - Console.WriteLine(exception.Message); - if (exception.InnerExceptions.Count < 1) + // Enumerate the exceptions only if there is more than + // one because with one the message gets merged into the + // Aggregate exception message. + foreach (Exception item in exception.InnerExceptions) { - // Enumerate the exceptions only if there is more than - // one because with one the message gets merged into the - // Aggregate exception message. - foreach (Exception item in exception.InnerExceptions) - { - Console.WriteLine("\t{0}: {1}", - item.GetType(), item.Message); - } + Console.WriteLine("\t{0}: {1}", + item.GetType(), item.Message); } } } diff --git a/src/Chapter14/Listing14.11.UsingTheAssignmentOperationRatherThanPlusEquals.cs b/src/Chapter14/Listing14.11.UsingTheAssignmentOperationRatherThanPlusEquals.cs index 8849d3b91..9905d0e9d 100644 --- a/src/Chapter14/Listing14.11.UsingTheAssignmentOperationRatherThanPlusEquals.cs +++ b/src/Chapter14/Listing14.11.UsingTheAssignmentOperationRatherThanPlusEquals.cs @@ -1,37 +1,36 @@ using AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_02; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_11; + +using System; +using Listing14_01; +#region INCLUDE +public class Program { - using System; - using Listing14_01; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - thermostat.OnTemperatureChange = - heater.OnTemperatureChanged; + thermostat.OnTemperatureChange = + heater.OnTemperatureChanged; - // Bug: Assignment operator overrides - // previous assignment - #region HIGHLIGHT - thermostat.OnTemperatureChange = - cooler.OnTemperatureChanged; - #endregion HIGHLIGHT + // Bug: Assignment operator overrides + // previous assignment + #region HIGHLIGHT + thermostat.OnTemperatureChange = + cooler.OnTemperatureChanged; + #endregion HIGHLIGHT - Console.Write("Enter temperature: "); - string? temperature = Console.ReadLine(); - if (!int.TryParse(temperature, out int currentTemperature)) - { - Console.WriteLine($"'{temperature}' is not a valid integer."); - return; - } - thermostat.CurrentTemperature = currentTemperature; + Console.Write("Enter temperature: "); + string? temperature = Console.ReadLine(); + if (!int.TryParse(temperature, out int currentTemperature)) + { + Console.WriteLine($"'{temperature}' is not a valid integer."); + return; } + thermostat.CurrentTemperature = currentTemperature; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.12.FiringTheEventFromOutsideTheEventContainer.cs b/src/Chapter14/Listing14.12.FiringTheEventFromOutsideTheEventContainer.cs index 9c060eccf..5481f23d6 100644 --- a/src/Chapter14/Listing14.12.FiringTheEventFromOutsideTheEventContainer.cs +++ b/src/Chapter14/Listing14.12.FiringTheEventFromOutsideTheEventContainer.cs @@ -1,27 +1,26 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_12; + +using Listing14_01; +using Listing14_10; +#region INCLUDE +public class Program { - using Listing14_01; - using Listing14_10; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - Thermostat thermostat = new Thermostat(); - Heater heater = new Heater(60); - Cooler cooler = new Cooler(80); + Thermostat thermostat = new Thermostat(); + Heater heater = new Heater(60); + Cooler cooler = new Cooler(80); - thermostat.OnTemperatureChange += - heater.OnTemperatureChanged; + thermostat.OnTemperatureChange += + heater.OnTemperatureChanged; - thermostat.OnTemperatureChange += - cooler.OnTemperatureChanged; + thermostat.OnTemperatureChange += + cooler.OnTemperatureChanged; - // Bug: Should not be allowed - #region HIGHLIGHT - thermostat.OnTemperatureChange(42); - #endregion HIGHLIGHT - } + // Bug: Should not be allowed + #region HIGHLIGHT + thermostat.OnTemperatureChange(42); + #endregion HIGHLIGHT } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.13.UsingTheEventKeywordWithTheEventCodingPattern.cs b/src/Chapter14/Listing14.13.UsingTheEventKeywordWithTheEventCodingPattern.cs index e8e2372df..dc2f3e689 100644 --- a/src/Chapter14/Listing14.13.UsingTheEventKeywordWithTheEventCodingPattern.cs +++ b/src/Chapter14/Listing14.13.UsingTheEventKeywordWithTheEventCodingPattern.cs @@ -1,35 +1,34 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_13 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_13; + +using System; #pragma warning disable 67 // OnTemperatureChange is declared but never used - #region INCLUDE - public class Thermostat +#region INCLUDE +public class Thermostat +{ + #region HIGHLIGHT + public class TemperatureArgs : System.EventArgs { - #region HIGHLIGHT - public class TemperatureArgs : System.EventArgs + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - NewTemperature = newTemperature; - } - - public float NewTemperature { get; set; } + NewTemperature = newTemperature; } - // Define the event publisher - public event EventHandler OnTemperatureChange = - delegate { }; - #endregion HIGHLIGHT + public float NewTemperature { get; set; } + } - public float CurrentTemperature - #region EXCLUDE - { - get { return _CurrentTemperature; } - set { _CurrentTemperature = value; } - } - #endregion EXCLUDE - private float _CurrentTemperature; + // Define the event publisher + public event EventHandler OnTemperatureChange = + delegate { }; + #endregion HIGHLIGHT + + public float CurrentTemperature + #region EXCLUDE + { + get { return _CurrentTemperature; } + set { _CurrentTemperature = value; } } - #endregion INCLUDE + #endregion EXCLUDE + private float _CurrentTemperature; +} +#endregion INCLUDE #pragma warning restore 67 -} \ No newline at end of file diff --git a/src/Chapter14/Listing14.14.DeclaringAGenericDelegateType.cs b/src/Chapter14/Listing14.14.DeclaringAGenericDelegateType.cs index 48f9d27f7..383150da2 100644 --- a/src/Chapter14/Listing14.14.DeclaringAGenericDelegateType.cs +++ b/src/Chapter14/Listing14.14.DeclaringAGenericDelegateType.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_14 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_14; + +using System; - public class Thermostat - { - #region INCLUDE - public delegate void EventHandler( - object sender, TEventArgs e) - where TEventArgs : EventArgs; - #endregion INCLUDE - } +public class Thermostat +{ + #region INCLUDE + public delegate void EventHandler( + object sender, TEventArgs e) + where TEventArgs : EventArgs; + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter14/Listing14.15.FiringTheEventNotification.cs b/src/Chapter14/Listing14.15.FiringTheEventNotification.cs index c430c7bb3..4b2c06d02 100644 --- a/src/Chapter14/Listing14.15.FiringTheEventNotification.cs +++ b/src/Chapter14/Listing14.15.FiringTheEventNotification.cs @@ -1,44 +1,43 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_15; + +using System; +#region INCLUDE +public class Thermostat +#region EXCLUDE { - using System; - #region INCLUDE - public class Thermostat - #region EXCLUDE + public class TemperatureArgs : System.EventArgs { - public class TemperatureArgs : System.EventArgs + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - NewTemperature = newTemperature; - } - - public float NewTemperature { get; set; } + NewTemperature = newTemperature; } - // Define the event publisher - public event EventHandler OnTemperatureChange = - delegate { }; - #endregion EXCLUDE + public float NewTemperature { get; set; } + } + + // Define the event publisher + public event EventHandler OnTemperatureChange = + delegate { }; + #endregion EXCLUDE - public float CurrentTemperature + public float CurrentTemperature + { + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + if(value != CurrentTemperature) { - if(value != CurrentTemperature) - { - _CurrentTemperature = value; - // If there are any subscribers, - // notify them of changes in - // temperature by invoking said subcribers - #region HIGHLIGHT - OnTemperatureChange?.Invoke( - this, new TemperatureArgs(value)); - #endregion HIGHLIGHT - } + _CurrentTemperature = value; + // If there are any subscribers, + // notify them of changes in + // temperature by invoking said subcribers + #region HIGHLIGHT + OnTemperatureChange?.Invoke( + this, new TemperatureArgs(value)); + #endregion HIGHLIGHT } } - private float _CurrentTemperature; } - #endregion INCLUDE -} \ No newline at end of file + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.16.UsingCustomDelegateType.cs b/src/Chapter14/Listing14.16.UsingCustomDelegateType.cs index 388fcedc8..1c0005207 100644 --- a/src/Chapter14/Listing14.16.UsingCustomDelegateType.cs +++ b/src/Chapter14/Listing14.16.UsingCustomDelegateType.cs @@ -1,46 +1,45 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_16; + +#region INCLUDE +public class Thermostat { - #region INCLUDE - public class Thermostat + public class TemperatureArgs : System.EventArgs { - public class TemperatureArgs : System.EventArgs + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - NewTemperature = newTemperature; - } - - public float NewTemperature { get; set; } + NewTemperature = newTemperature; } - #region HIGHLIGHT - public delegate void TemperatureChangeHandler( - object sender, TemperatureArgs newTemperature); + public float NewTemperature { get; set; } + } + + #region HIGHLIGHT + public delegate void TemperatureChangeHandler( + object sender, TemperatureArgs newTemperature); - public event TemperatureChangeHandler? - OnTemperatureChange; - #endregion HIGHLIGHT + public event TemperatureChangeHandler? + OnTemperatureChange; + #endregion HIGHLIGHT - public float CurrentTemperature - #region EXCLUDE + public float CurrentTemperature + #region EXCLUDE + { + get { return _CurrentTemperature; } + set { - get { return _CurrentTemperature; } - set + if(value != CurrentTemperature) { - if(value != CurrentTemperature) - { - _CurrentTemperature = value; - // If there are any subscribers - // then notify them of changes in - // temperature - // Call subscribers - OnTemperatureChange?.Invoke( - this, new TemperatureArgs(value)); - } + _CurrentTemperature = value; + // If there are any subscribers + // then notify them of changes in + // temperature + // Call subscribers + OnTemperatureChange?.Invoke( + this, new TemperatureArgs(value)); } } - #endregion EXCLUDE - private float _CurrentTemperature; } - #endregion INCLUDE -} \ No newline at end of file + #endregion EXCLUDE + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.17.DeclaringTheOnTemperatureChangeEvent.cs b/src/Chapter14/Listing14.17.DeclaringTheOnTemperatureChangeEvent.cs index 7b86a5a47..45c55678d 100644 --- a/src/Chapter14/Listing14.17.DeclaringTheOnTemperatureChangeEvent.cs +++ b/src/Chapter14/Listing14.17.DeclaringTheOnTemperatureChangeEvent.cs @@ -2,25 +2,24 @@ #pragma warning disable CS0067 // The event is never used #pragma warning disable CS0469 // Field is never assigned to, and will always have its default value - null -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_17; + +using System; +// In an actual implementation we would utilize this event +#region INCLUDE +public class Thermostat +#region EXCLUDE { - using System; - // In an actual implementation we would utilize this event - #region INCLUDE - public class Thermostat - #region EXCLUDE + public class TemperatureArgs : System.EventArgs { - public class TemperatureArgs : System.EventArgs + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - NewTemperature = newTemperature; - } - - public float NewTemperature { get; set; } + NewTemperature = newTemperature; } - #endregion EXCLUDE - public event EventHandler? OnTemperatureChange; + + public float NewTemperature { get; set; } } - #endregion INCLUDE -} \ No newline at end of file + #endregion EXCLUDE + public event EventHandler? OnTemperatureChange; +} +#endregion INCLUDE diff --git a/src/Chapter14/Listing14.18.CSharpConceptualEquivalentOfEventCILCode.cs b/src/Chapter14/Listing14.18.CSharpConceptualEquivalentOfEventCILCode.cs index cf1431034..101c0df2d 100644 --- a/src/Chapter14/Listing14.18.CSharpConceptualEquivalentOfEventCILCode.cs +++ b/src/Chapter14/Listing14.18.CSharpConceptualEquivalentOfEventCILCode.cs @@ -3,61 +3,60 @@ #pragma warning disable IDE0060 // Remove unused parameter #pragma warning disable IDE1006 // Naming Styles -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_18; + +using System; +#region INCLUDE +public class Thermostat +#region EXCLUDE { - using System; - #region INCLUDE - public class Thermostat - #region EXCLUDE + // Used to suppress warning CS0469: field never assigned to, and + // will always have its default value null. + public Thermostat(EventHandler? onTemperatureChange) { - // Used to suppress warning CS0469: field never assigned to, and - // will always have its default value null. - public Thermostat(EventHandler? onTemperatureChange) - { - _OnTemperatureChange = onTemperatureChange; - } + _OnTemperatureChange = onTemperatureChange; + } + + // ... + #endregion EXCLUDE + // Declaring the delegate field to save the + // list of subscribers + private EventHandler? _OnTemperatureChange; + + public void add_OnTemperatureChange( + EventHandler handler) + { + System.Delegate.Combine(_OnTemperatureChange, handler); + } - // ... - #endregion EXCLUDE - // Declaring the delegate field to save the - // list of subscribers - private EventHandler? _OnTemperatureChange; + public void remove_OnTemperatureChange( + EventHandler handler) + { + System.Delegate.Remove(_OnTemperatureChange, handler); + } - public void add_OnTemperatureChange( - EventHandler handler) + #if ConceptualEquivalentCode + public event EventHandler OnTemperatureChange + { + //Would cause a compiler error + add { - System.Delegate.Combine(_OnTemperatureChange, handler); + add_OnTemperatureChange(value); } - - public void remove_OnTemperatureChange( - EventHandler handler) + //Would cause a compiler error + remove { - System.Delegate.Remove(_OnTemperatureChange, handler); + remove_OnTemperatureChange(value); } + } + #endif // ConceptualEquivalentCode + #endregion INCLUDE - #if ConceptualEquivalentCode - public event EventHandler OnTemperatureChange - { - //Would cause a compiler error - add - { - add_OnTemperatureChange(value); - } - //Would cause a compiler error - remove - { - remove_OnTemperatureChange(value); - } - } - #endif // ConceptualEquivalentCode - #endregion INCLUDE - - public class TemperatureArgs : System.EventArgs + public class TemperatureArgs : System.EventArgs + { + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - } - } + } } \ No newline at end of file diff --git a/src/Chapter14/Listing14.19.CustomAddAndRemoveHandlers.cs b/src/Chapter14/Listing14.19.CustomAddAndRemoveHandlers.cs index c5e96db1b..1e420fa9e 100644 --- a/src/Chapter14/Listing14.19.CustomAddAndRemoveHandlers.cs +++ b/src/Chapter14/Listing14.19.CustomAddAndRemoveHandlers.cs @@ -1,62 +1,61 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter14.Listing14_19; + +#region INCLUDE +public class Thermostat { - #region INCLUDE - public class Thermostat + public class TemperatureArgs : System.EventArgs + #region EXCLUDE { - public class TemperatureArgs : System.EventArgs - #region EXCLUDE + public TemperatureArgs(float newTemperature) { - public TemperatureArgs(float newTemperature) - { - NewTemperature = newTemperature; - } + NewTemperature = newTemperature; + } - public float NewTemperature { get; set; } + public float NewTemperature { get; set; } + } + + // Define the delegate data type + public delegate void EventHandler( + object sender, TemperatureArgs newTemperature); + #endregion EXCLUDE + #region HIGHLIGHT + // Define the event publisher + public event EventHandler OnTemperatureChange + { + add + { + _OnTemperatureChange = + (EventHandler) + System.Delegate.Combine(value, _OnTemperatureChange); } - - // Define the delegate data type - public delegate void EventHandler( - object sender, TemperatureArgs newTemperature); - #endregion EXCLUDE - #region HIGHLIGHT - // Define the event publisher - public event EventHandler OnTemperatureChange + remove { - add - { - _OnTemperatureChange = - (EventHandler) - System.Delegate.Combine(value, _OnTemperatureChange); - } - remove - { - _OnTemperatureChange = - (EventHandler?) - System.Delegate.Remove(_OnTemperatureChange, value); - } + _OnTemperatureChange = + (EventHandler?) + System.Delegate.Remove(_OnTemperatureChange, value); } - protected EventHandler? _OnTemperatureChange; - #endregion HIGHLIGHT + } + protected EventHandler? _OnTemperatureChange; + #endregion HIGHLIGHT - public float CurrentTemperature - #region EXCLUDE + public float CurrentTemperature + #region EXCLUDE + { + set { - set + if (value != CurrentTemperature) { - if (value != CurrentTemperature) - { - _CurrentTemperature = value; - // If there are any subscribers, - // notify them of changes in - // temperature by invoking said subcribers - _OnTemperatureChange?.Invoke( // C# 6.0 - this, new TemperatureArgs(value)); - } + _CurrentTemperature = value; + // If there are any subscribers, + // notify them of changes in + // temperature by invoking said subcribers + _OnTemperatureChange?.Invoke( // C# 6.0 + this, new TemperatureArgs(value)); } - get { return _CurrentTemperature; } } - #endregion EXCLUDE - private float _CurrentTemperature; + get { return _CurrentTemperature; } } - #endregion INCLUDE -} \ No newline at end of file + #endregion EXCLUDE + private float _CurrentTemperature; +} +#endregion INCLUDE diff --git a/src/Chapter15/EmployeeData.cs b/src/Chapter15/EmployeeData.cs index b9a606125..681db71cd 100644 --- a/src/Chapter15/EmployeeData.cs +++ b/src/Chapter15/EmployeeData.cs @@ -1,62 +1,61 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; + +public class Department { - public class Department + public long Id { get; } + public string Name { get; } + public Department(string name, long id) + { + Id = id; + Name = name ?? throw new ArgumentNullException(nameof(name)); + } + public override string ToString() { - public long Id { get; } - public string Name { get; } - public Department(string name, long id) - { - Id = id; - Name = name ?? throw new ArgumentNullException(nameof(name)); - } - public override string ToString() - { - return Name; - } + return Name; } +} - public class Employee +public class Employee +{ + public int Id { get; } + public string Name { get; } + public string Title { get; } + public int DepartmentId { get; } + public Employee( + string name, string title, int departmentId) { - public int Id { get; } - public string Name { get; } - public string Title { get; } - public int DepartmentId { get; } - public Employee( - string name, string title, int departmentId) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - Title = title ?? throw new ArgumentNullException(nameof(title)); - DepartmentId = departmentId; - } - public override string ToString() - { - return $"{ Name } ({ Title })"; - } + Name = name ?? throw new ArgumentNullException(nameof(name)); + Title = title ?? throw new ArgumentNullException(nameof(title)); + DepartmentId = departmentId; } + public override string ToString() + { + return $"{ Name } ({ Title })"; + } +} - public static class CorporateData +public static class CorporateData +{ + public static readonly Department[] Departments = + new Department[] { - public static readonly Department[] Departments = - new Department[] - { - new Department("Corporate", 0), - new Department("Human Resources", 1), - new Department("Engineering", 2), - new Department("Information Technology", 3), - new Department("Philanthropy", 4), - new Department("Marketing", 5), - }; + new Department("Corporate", 0), + new Department("Human Resources", 1), + new Department("Engineering", 2), + new Department("Information Technology", 3), + new Department("Philanthropy", 4), + new Department("Marketing", 5), + }; - public static readonly Employee[] Employees = new Employee[] - { - new Employee("Mark Michaelis", "Chief Computer Nerd", 0), - new Employee("Michael Stokesbary", "Senior Computer Wizard", 2), - new Employee("Brian Jones", "Enterprise Integration Guru", 2), - new Employee("Anne Beard", "HR Director", 1), - new Employee("Pat Dever", "Enterprise Architect", 3), - new Employee("Kevin Bost", "Programmer Extraordinaire", 2), - new Employee("Thomas Heavey", "Software Architect", 2), - new Employee("Eric Edmonds", "Philanthropy Coordinator", 4) - }; - } + public static readonly Employee[] Employees = new Employee[] + { + new Employee("Mark Michaelis", "Chief Computer Nerd", 0), + new Employee("Michael Stokesbary", "Senior Computer Wizard", 2), + new Employee("Brian Jones", "Enterprise Integration Guru", 2), + new Employee("Anne Beard", "HR Director", 1), + new Employee("Pat Dever", "Enterprise Architect", 3), + new Employee("Kevin Bost", "Programmer Extraordinaire", 2), + new Employee("Thomas Heavey", "Software Architect", 2), + new Employee("Eric Edmonds", "Philanthropy Coordinator", 4) + }; } diff --git a/src/Chapter15/Listing15.01.CollectionInitialization.cs b/src/Chapter15/Listing15.01.CollectionInitialization.cs index 63710d3fa..b5a933ebf 100644 --- a/src/Chapter15/Listing15.01.CollectionInitialization.cs +++ b/src/Chapter15/Listing15.01.CollectionInitialization.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_01 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_01; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + List sevenWorldBlunders; + sevenWorldBlunders = new List() { - List sevenWorldBlunders; - sevenWorldBlunders = new List() - { - // Quotes from Gandhi - "Wealth without work", - "Pleasure without conscience", - "Knowledge without character", - "Commerce without morality", - "Science without humanity", - "Worship without sacrifice", - "Politics without principle" - }; + // Quotes from Gandhi + "Wealth without work", + "Pleasure without conscience", + "Knowledge without character", + "Commerce without morality", + "Science without humanity", + "Worship without sacrifice", + "Politics without principle" + }; - Print(sevenWorldBlunders); - } + Print(sevenWorldBlunders); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.02.DictionaryInitializers.cs b/src/Chapter15/Listing15.02.DictionaryInitializers.cs index 6077961c7..42cabf505 100644 --- a/src/Chapter15/Listing15.02.DictionaryInitializers.cs +++ b/src/Chapter15/Listing15.02.DictionaryInitializers.cs @@ -1,45 +1,44 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_02; + +#region INCLUDE +using System; +using System.Collections.Generic; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - #endregion EXCLUDE + #endregion EXCLUDE #if !PRECSHARP6 - Dictionary colorMap = - new Dictionary - { - ["Error"] = ConsoleColor.Red, - ["Warning"] = ConsoleColor.Yellow, - ["Information"] = ConsoleColor.Green, - ["Verbose"] = ConsoleColor.White - }; + Dictionary colorMap = + new Dictionary + { + ["Error"] = ConsoleColor.Red, + ["Warning"] = ConsoleColor.Yellow, + ["Information"] = ConsoleColor.Green, + ["Verbose"] = ConsoleColor.White + }; #else - Dictionary colorMap = - new Dictionary - { - {"Error", ConsoleColor.Red }, - {"Warning", ConsoleColor.Yellow }, - {"Information", ConsoleColor.Green }, - {"Verbose", ConsoleColor.White} - }; + Dictionary colorMap = + new Dictionary + { + {"Error", ConsoleColor.Red }, + {"Warning", ConsoleColor.Yellow }, + {"Information", ConsoleColor.Green }, + {"Verbose", ConsoleColor.White} + }; #endif - #endregion INCLUDE + #endregion INCLUDE - Print(colorMap); - } + Print(colorMap); + } - private static void Print(IEnumerable> items) + private static void Print(IEnumerable> items) + { + foreach(KeyValuePair item in items) { - foreach(KeyValuePair item in items) - { - Console.ForegroundColor = item.Value; - Console.WriteLine(item.Key); - } + Console.ForegroundColor = item.Value; + Console.WriteLine(item.Key); } } } diff --git a/src/Chapter15/Listing15.03.ForeachWithArrays.cs b/src/Chapter15/Listing15.03.ForeachWithArrays.cs index 234c9b700..4a7c3105e 100644 --- a/src/Chapter15/Listing15.03.ForeachWithArrays.cs +++ b/src/Chapter15/Listing15.03.ForeachWithArrays.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_03 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_03; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; + #region INCLUDE + int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; - foreach(int item in array) - { - Console.WriteLine(item); - } - #endregion INCLUDE + foreach(int item in array) + { + Console.WriteLine(item); } + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.04.CompiledImplementationOfForeachWithArrays.cs b/src/Chapter15/Listing15.04.CompiledImplementationOfForeachWithArrays.cs index 4325dc0df..d43f3cadc 100644 --- a/src/Chapter15/Listing15.04.CompiledImplementationOfForeachWithArrays.cs +++ b/src/Chapter15/Listing15.04.CompiledImplementationOfForeachWithArrays.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_04 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_04; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - int[] tempArray; - int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; + #region INCLUDE + int[] tempArray; + int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; - tempArray = array; - for(int counter = 0; (counter < tempArray.Length); counter++) - { - int item = tempArray[counter]; + tempArray = array; + for(int counter = 0; (counter < tempArray.Length); counter++) + { + int item = tempArray[counter]; - Console.WriteLine(item); - } - #endregion INCLUDE + Console.WriteLine(item); } + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.05.IteratingOverACollectionUsingWhile.cs b/src/Chapter15/Listing15.05.IteratingOverACollectionUsingWhile.cs index 0bfee2ac4..1e0578ee4 100644 --- a/src/Chapter15/Listing15.05.IteratingOverACollectionUsingWhile.cs +++ b/src/Chapter15/Listing15.05.IteratingOverACollectionUsingWhile.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_05 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_05; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - System.Collections.Generic.Stack stack = - new System.Collections.Generic.Stack(); - int number; - // ... + #region INCLUDE + System.Collections.Generic.Stack stack = + new System.Collections.Generic.Stack(); + int number; + // ... - // This code is conceptual, not the actual code - #if ConceptualCode - while(stack.MoveNext()) - { - number = stack.Current(); - Console.WriteLine(number); - } - #endif // ConceptualCode + // This code is conceptual, not the actual code + #if ConceptualCode + while(stack.MoveNext()) + { + number = stack.Current(); + Console.WriteLine(number); + } + #endif // ConceptualCode - #endregion INCLUDE + #endregion INCLUDE - // Actual Code - while(stack.Pop() != -1) //this is actually not the right logic, but the point is the while, not stack - { - number = stack.Peek(); - Console.WriteLine(number); - } + // Actual Code + while(stack.Pop() != -1) //this is actually not the right logic, but the point is the while, not stack + { + number = stack.Peek(); + Console.WriteLine(number); } } } diff --git a/src/Chapter15/Listing15.06.ASeparateEnumeratorMaintainingStateDuringAnIteration.cs b/src/Chapter15/Listing15.06.ASeparateEnumeratorMaintainingStateDuringAnIteration.cs index 6352b15a3..29b6033ad 100644 --- a/src/Chapter15/Listing15.06.ASeparateEnumeratorMaintainingStateDuringAnIteration.cs +++ b/src/Chapter15/Listing15.06.ASeparateEnumeratorMaintainingStateDuringAnIteration.cs @@ -1,30 +1,29 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_06 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_06; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - System.Collections.Generic.Stack stack = - new System.Collections.Generic.Stack(); - int number; - System.Collections.Generic.Stack.Enumerator - enumerator; + #region INCLUDE + System.Collections.Generic.Stack stack = + new System.Collections.Generic.Stack(); + int number; + System.Collections.Generic.Stack.Enumerator + enumerator; - // ... + // ... - // If IEnumerable is implemented explicitly, - // then a cast is required - // ((IEnumerable)stack).GetEnumerator(); - enumerator = stack.GetEnumerator(); - while(enumerator.MoveNext()) - { - number = enumerator.Current; - Console.WriteLine(number); - } - #endregion INCLUDE + // If IEnumerable is implemented explicitly, + // then a cast is required + // ((IEnumerable)stack).GetEnumerator(); + enumerator = stack.GetEnumerator(); + while(enumerator.MoveNext()) + { + number = enumerator.Current; + Console.WriteLine(number); } + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.07.CompiledResultOfForeachOnCollections.cs b/src/Chapter15/Listing15.07.CompiledResultOfForeachOnCollections.cs index 367390976..b4c831b6d 100644 --- a/src/Chapter15/Listing15.07.CompiledResultOfForeachOnCollections.cs +++ b/src/Chapter15/Listing15.07.CompiledResultOfForeachOnCollections.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_07 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_07; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - System.Collections.Generic.Stack stack = - new System.Collections.Generic.Stack(); - System.Collections.Generic.Stack.Enumerator enumerator; - IDisposable disposable; + #region INCLUDE + System.Collections.Generic.Stack stack = + new System.Collections.Generic.Stack(); + System.Collections.Generic.Stack.Enumerator enumerator; + IDisposable disposable; - enumerator = stack.GetEnumerator(); - try + enumerator = stack.GetEnumerator(); + try + { + int number; + while(enumerator.MoveNext()) { - int number; - while(enumerator.MoveNext()) - { - number = enumerator.Current; - Console.WriteLine(number); - } + number = enumerator.Current; + Console.WriteLine(number); } - finally - { - // Explicit cast used for IEnumerator - disposable = (IDisposable)enumerator; - disposable.Dispose(); + } + finally + { + // Explicit cast used for IEnumerator + disposable = (IDisposable)enumerator; + disposable.Dispose(); - // IEnumerator will use the as operator unless IDisposable - // support is known at compile time - // disposable = (enumerator as IDisposable); - // if (disposable != null) - // { - // disposable.Dispose(); - // } - } - #endregion INCLUDE + // IEnumerator will use the as operator unless IDisposable + // support is known at compile time + // disposable = (enumerator as IDisposable); + // if (disposable != null) + // { + // disposable.Dispose(); + // } } + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.08.ErrorHandlingAndResourceCleanupWithUsing.cs b/src/Chapter15/Listing15.08.ErrorHandlingAndResourceCleanupWithUsing.cs index 4de6f3bbc..a72bbd2b3 100644 --- a/src/Chapter15/Listing15.08.ErrorHandlingAndResourceCleanupWithUsing.cs +++ b/src/Chapter15/Listing15.08.ErrorHandlingAndResourceCleanupWithUsing.cs @@ -1,29 +1,28 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_08 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_08; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region INCLUDE - System.Collections.Generic.Stack stack = - new System.Collections.Generic.Stack(); - int number; + #region INCLUDE + System.Collections.Generic.Stack stack = + new System.Collections.Generic.Stack(); + int number; - #region HIGHLIGHT - using ( - System.Collections.Generic.Stack.Enumerator - enumerator = stack.GetEnumerator()) - #endregion HIGHLIGHT + #region HIGHLIGHT + using ( + System.Collections.Generic.Stack.Enumerator + enumerator = stack.GetEnumerator()) + #endregion HIGHLIGHT + { + while (enumerator.MoveNext()) { - while (enumerator.MoveNext()) - { - number = enumerator.Current; - Console.WriteLine(number); - } + number = enumerator.Current; + Console.WriteLine(number); } - #endregion INCLUDE } + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.09.SampleClassesForUseWithStandardQueryOperators.cs b/src/Chapter15/Listing15.09.SampleClassesForUseWithStandardQueryOperators.cs index 2e57dfc64..8e23f0522 100644 --- a/src/Chapter15/Listing15.09.SampleClassesForUseWithStandardQueryOperators.cs +++ b/src/Chapter15/Listing15.09.SampleClassesForUseWithStandardQueryOperators.cs @@ -1,30 +1,29 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_09 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_09; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - IEnumerable patents = PatentData.Patents; - Print(patents); + IEnumerable patents = PatentData.Patents; + Print(patents); - Console.WriteLine(); + Console.WriteLine(); - IEnumerable inventors = PatentData.Inventors; - Print(inventors); - } + IEnumerable inventors = PatentData.Inventors; + Print(inventors); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.10.FilteringWithSystem.Linq.Enumerable.Where.cs b/src/Chapter15/Listing15.10.FilteringWithSystem.Linq.Enumerable.Where.cs index f42508714..6dc6552e9 100644 --- a/src/Chapter15/Listing15.10.FilteringWithSystem.Linq.Enumerable.Where.cs +++ b/src/Chapter15/Listing15.10.FilteringWithSystem.Linq.Enumerable.Where.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_10 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_10; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - IEnumerable patents = PatentData.Patents; - #region HIGHLIGHT - patents = patents.Where( - patent => patent.YearOfPublication.StartsWith("18")); - #endregion HIGHLIGHT - Print(patents); - } - #region EXCLUDE + IEnumerable patents = PatentData.Patents; + #region HIGHLIGHT + patents = patents.Where( + patent => patent.YearOfPublication.StartsWith("18")); + #endregion HIGHLIGHT + Print(patents); + } + #region EXCLUDE - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } - #endregion EXCLUDE } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.11.ProjectionWithSystem.Linq.Enumerable.Select.cs b/src/Chapter15/Listing15.11.ProjectionWithSystem.Linq.Enumerable.Select.cs index ef7e79647..bf48a3d7e 100644 --- a/src/Chapter15/Listing15.11.ProjectionWithSystem.Linq.Enumerable.Select.cs +++ b/src/Chapter15/Listing15.11.ProjectionWithSystem.Linq.Enumerable.Select.cs @@ -1,35 +1,34 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_11 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_11; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - IEnumerable patents = PatentData.Patents; - IEnumerable patentsOf1800 = patents.Where( - patent => patent.YearOfPublication.StartsWith("18")); - #region HIGHLIGHT - IEnumerable items = patentsOf1800.Select( - patent => patent.ToString()); - #endregion HIGHLIGHT + IEnumerable patents = PatentData.Patents; + IEnumerable patentsOf1800 = patents.Where( + patent => patent.YearOfPublication.StartsWith("18")); + #region HIGHLIGHT + IEnumerable items = patentsOf1800.Select( + patent => patent.ToString()); + #endregion HIGHLIGHT - Print(items); - } - #region EXCLUDE + Print(items); + } + #region EXCLUDE - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } - #endregion EXCLUDE } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.12.ProjectionWithSystem.Linq.Enumerable.Select.cs b/src/Chapter15/Listing15.12.ProjectionWithSystem.Linq.Enumerable.Select.cs index 6f638234c..6e2d94369 100644 --- a/src/Chapter15/Listing15.12.ProjectionWithSystem.Linq.Enumerable.Select.cs +++ b/src/Chapter15/Listing15.12.ProjectionWithSystem.Linq.Enumerable.Select.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_12 -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_12; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - string rootDirectory = Directory.GetCurrentDirectory(); - string searchPattern = "*"; ; - #region INCLUDE - //... - IEnumerable fileList = Directory.EnumerateFiles( - rootDirectory, searchPattern); - IEnumerable files = fileList.Select( - file => new FileInfo(file)); - //... - #endregion INCLUDE - Print(files); - } + string rootDirectory = Directory.GetCurrentDirectory(); + string searchPattern = "*"; ; + #region INCLUDE + //... + IEnumerable fileList = Directory.EnumerateFiles( + rootDirectory, searchPattern); + IEnumerable files = fileList.Select( + file => new FileInfo(file)); + //... + #endregion INCLUDE + Print(files); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach (T item in items) { - foreach (T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } } diff --git a/src/Chapter15/Listing15.13.ProjectionToATuple.cs b/src/Chapter15/Listing15.13.ProjectionToATuple.cs index 58f6fd7a5..17ef2ecc9 100644 --- a/src/Chapter15/Listing15.13.ProjectionToATuple.cs +++ b/src/Chapter15/Listing15.13.ProjectionToATuple.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_13 -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_13; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - string rootDirectory = Directory.GetCurrentDirectory(); - string searchPattern = "*"; - #region INCLUDE - //... - IEnumerable fileList = Directory.EnumerateFiles( - rootDirectory, searchPattern); - #region HIGHLIGHT - IEnumerable<(string FileName, long Size)> items = fileList.Select( - file => - { - FileInfo fileInfo = new FileInfo(file); - return ( - FileName: fileInfo.Name, - Size: fileInfo.Length - ); - }); - #endregion HIGHLIGHT - //... - #endregion INCLUDE + string rootDirectory = Directory.GetCurrentDirectory(); + string searchPattern = "*"; + #region INCLUDE + //... + IEnumerable fileList = Directory.EnumerateFiles( + rootDirectory, searchPattern); + #region HIGHLIGHT + IEnumerable<(string FileName, long Size)> items = fileList.Select( + file => + { + FileInfo fileInfo = new FileInfo(file); + return ( + FileName: fileInfo.Name, + Size: fileInfo.Length + ); + }); + #endregion HIGHLIGHT + //... + #endregion INCLUDE - Print(items); - } + Print(items); + } - private static void Print(IEnumerable<(string FileName, long Size)> items) + private static void Print(IEnumerable<(string FileName, long Size)> items) + { + foreach((string FileName, long Size) item in items) { - foreach((string FileName, long Size) item in items) - { - Console.WriteLine($"FileName = { item.FileName }, Size = { item.Size }"); - } + Console.WriteLine($"FileName = { item.FileName }, Size = { item.Size }"); } } } diff --git a/src/Chapter15/Listing15.14.ExecutingLinqQueriesInParallel.cs b/src/Chapter15/Listing15.14.ExecutingLinqQueriesInParallel.cs index cfdad9bc2..c46078b12 100644 --- a/src/Chapter15/Listing15.14.ExecutingLinqQueriesInParallel.cs +++ b/src/Chapter15/Listing15.14.ExecutingLinqQueriesInParallel.cs @@ -1,45 +1,44 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_14 -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_14; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - string rootDirectory = Directory.GetCurrentDirectory(); - string searchPattern = "*"; - #region INCLUDE - //... - IEnumerable fileList = Directory.EnumerateFiles( - rootDirectory, searchPattern); - #region HIGHLIGHT - var items = fileList.AsParallel().Select( - #endregion HIGHLIGHT - file => + string rootDirectory = Directory.GetCurrentDirectory(); + string searchPattern = "*"; + #region INCLUDE + //... + IEnumerable fileList = Directory.EnumerateFiles( + rootDirectory, searchPattern); + #region HIGHLIGHT + var items = fileList.AsParallel().Select( + #endregion HIGHLIGHT + file => + { + FileInfo fileInfo = new FileInfo(file); + return new { - FileInfo fileInfo = new FileInfo(file); - return new - { - FileName = fileInfo.Name, - Size = fileInfo.Length - }; - }); - //... - #endregion INCLUDE + FileName = fileInfo.Name, + Size = fileInfo.Length + }; + }); + //... + #endregion INCLUDE - Print(items); - } + Print(items); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } } diff --git a/src/Chapter15/Listing15.15.CountingItemsWithCount.cs b/src/Chapter15/Listing15.15.CountingItemsWithCount.cs index 1d5af52c6..43e4411db 100644 --- a/src/Chapter15/Listing15.15.CountingItemsWithCount.cs +++ b/src/Chapter15/Listing15.15.CountingItemsWithCount.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_15 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_15; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - IEnumerable patents = PatentData.Patents; - #region HIGHLIGHT - Console.WriteLine($"Patent Count: { patents.Count() }"); - #endregion HIGHLIGHT - Console.WriteLine($@"Patent Count in 1800s: { - patents.Count(patent => - patent.YearOfPublication.StartsWith("18"))}"); - #endregion INCLUDE - } + IEnumerable patents = PatentData.Patents; + #region HIGHLIGHT + Console.WriteLine($"Patent Count: { patents.Count() }"); + #endregion HIGHLIGHT + Console.WriteLine($@"Patent Count in 1800s: { + patents.Count(patent => + patent.YearOfPublication.StartsWith("18"))}"); + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.16.FilteringWithSystem.Linq.Enumerable.Where.cs b/src/Chapter15/Listing15.16.FilteringWithSystem.Linq.Enumerable.Where.cs index f4876b620..27eb7ea21 100644 --- a/src/Chapter15/Listing15.16.FilteringWithSystem.Linq.Enumerable.Where.cs +++ b/src/Chapter15/Listing15.16.FilteringWithSystem.Linq.Enumerable.Where.cs @@ -1,57 +1,56 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_16 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_16; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - IEnumerable patents = PatentData.Patents; - bool result; - patents = patents.Where( - patent => + #endregion EXCLUDE + IEnumerable patents = PatentData.Patents; + bool result; + patents = patents.Where( + patent => + { + if(result = + patent.YearOfPublication.StartsWith("18")) { - if(result = - patent.YearOfPublication.StartsWith("18")) - { - // Side effects like this in a predicate - // are used here to demonstrate a - // principle and should generally be - // avoided - Console.WriteLine("\t" + patent); - } - return result; - }); + // Side effects like this in a predicate + // are used here to demonstrate a + // principle and should generally be + // avoided + Console.WriteLine("\t" + patent); + } + return result; + }); - Console.WriteLine("1. Patents prior to the 1900s are:"); - foreach(Patent patent in patents) - { - } + Console.WriteLine("1. Patents prior to the 1900s are:"); + foreach(Patent patent in patents) + { + } - Console.WriteLine(); - Console.WriteLine( - "2. A second listing of patents prior to the 1900s:"); - Console.WriteLine( - $@" There are { patents.Count() - } patents prior to 1900."); + Console.WriteLine(); + Console.WriteLine( + "2. A second listing of patents prior to the 1900s:"); + Console.WriteLine( + $@" There are { patents.Count() + } patents prior to 1900."); - Console.WriteLine(); - Console.WriteLine( - "3. A third listing of patents prior to the 1900s:"); - patents = patents.ToArray(); - Console.Write(" There are "); - Console.WriteLine( - $"{ patents.Count() } patents prior to 1900."); + Console.WriteLine(); + Console.WriteLine( + "3. A third listing of patents prior to the 1900s:"); + patents = patents.ToArray(); + Console.Write(" There are "); + Console.WriteLine( + $"{ patents.Count() } patents prior to 1900."); - //... - #endregion INCLUDE - } + //... + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.17.OrderingWithSystem.Linq.Enumerable.OrderByAndThenBy.cs b/src/Chapter15/Listing15.17.OrderingWithSystem.Linq.Enumerable.OrderByAndThenBy.cs index f451bc2ba..6e5dddbf7 100644 --- a/src/Chapter15/Listing15.17.OrderingWithSystem.Linq.Enumerable.OrderByAndThenBy.cs +++ b/src/Chapter15/Listing15.17.OrderingWithSystem.Linq.Enumerable.OrderByAndThenBy.cs @@ -1,41 +1,40 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_17 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_17; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - IEnumerable items; - Patent[] patents = PatentData.Patents; - items = patents.OrderBy( - patent => patent.YearOfPublication) - .ThenBy( - patent => patent.Title); - Print(items); - Console.WriteLine(); + #endregion EXCLUDE + IEnumerable items; + Patent[] patents = PatentData.Patents; + items = patents.OrderBy( + patent => patent.YearOfPublication) + .ThenBy( + patent => patent.Title); + Print(items); + Console.WriteLine(); - items = patents.OrderByDescending( - patent => patent.YearOfPublication) - .ThenByDescending( - patent => patent.Title); - Print(items); + items = patents.OrderByDescending( + patent => patent.YearOfPublication) + .ThenByDescending( + patent => patent.Title); + Print(items); - //... - #endregion INCLUDE - } + //... + #endregion INCLUDE + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } } diff --git a/src/Chapter15/Listing15.18.SampleEmployeeAndDepartmentData.cs b/src/Chapter15/Listing15.18.SampleEmployeeAndDepartmentData.cs index ed81c80a6..974c337c1 100644 --- a/src/Chapter15/Listing15.18.SampleEmployeeAndDepartmentData.cs +++ b/src/Chapter15/Listing15.18.SampleEmployeeAndDepartmentData.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_18 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_18; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +using System; +using System.Collections.Generic; +#region INCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - using System; - using System.Collections.Generic; - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - IEnumerable departments = - CorporateData.Departments; - Print(departments); + IEnumerable departments = + CorporateData.Departments; + Print(departments); - Console.WriteLine(); + Console.WriteLine(); - IEnumerable employees = - CorporateData.Employees; - Print(employees); - } + IEnumerable employees = + CorporateData.Employees; + Print(employees); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.19.AnInnerJoinUsingSystem.Linq.Enumerable.Join.cs b/src/Chapter15/Listing15.19.AnInnerJoinUsingSystem.Linq.Enumerable.Join.cs index 617316975..65cf6e2a6 100644 --- a/src/Chapter15/Listing15.19.AnInnerJoinUsingSystem.Linq.Enumerable.Join.cs +++ b/src/Chapter15/Listing15.19.AnInnerJoinUsingSystem.Linq.Enumerable.Join.cs @@ -1,41 +1,40 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_19; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - Department[] departments = CorporateData.Departments; - Employee[] employees = CorporateData.Employees; + #endregion EXCLUDE + Department[] departments = CorporateData.Departments; + Employee[] employees = CorporateData.Employees; - IEnumerable<(int Id, string Name, string Title, - Department Department)> items = - employees.Join( - departments, - employee => employee.DepartmentId, - department => department.Id, - (employee, department) => ( - employee.Id, - employee.Name, - employee.Title, - department - )); + IEnumerable<(int Id, string Name, string Title, + Department Department)> items = + employees.Join( + departments, + employee => employee.DepartmentId, + department => department.Id, + (employee, department) => ( + employee.Id, + employee.Name, + employee.Title, + department + )); - foreach ((int Id, string Name, string Title, Department Department) item in items) - { - Console.WriteLine( - $"{item.Name} ({item.Title})"); - Console.WriteLine("\t" + item.Department); - } + foreach ((int Id, string Name, string Title, Department Department) item in items) + { + Console.WriteLine( + $"{item.Name} ({item.Title})"); + Console.WriteLine("\t" + item.Department); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter15/Listing15.20.AnotherInnerJoinWithSystem.Linq.Enumerable.Join.cs b/src/Chapter15/Listing15.20.AnotherInnerJoinWithSystem.Linq.Enumerable.Join.cs index 5bceb28ab..eef9982c5 100644 --- a/src/Chapter15/Listing15.20.AnotherInnerJoinWithSystem.Linq.Enumerable.Join.cs +++ b/src/Chapter15/Listing15.20.AnotherInnerJoinWithSystem.Linq.Enumerable.Join.cs @@ -1,39 +1,38 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_20 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_20; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - Department[] departments = CorporateData.Departments; - Employee[] employees = CorporateData.Employees; + #endregion EXCLUDE + Department[] departments = CorporateData.Departments; + Employee[] employees = CorporateData.Employees; - IEnumerable<(long Id, string Name, Employee Employee)> items = - departments.Join( - employees, - department => department.Id, - employee => employee.DepartmentId, - (department, employee) => ( - department.Id, - department.Name, - Employee: employee) - ); + IEnumerable<(long Id, string Name, Employee Employee)> items = + departments.Join( + employees, + department => department.Id, + employee => employee.DepartmentId, + (department, employee) => ( + department.Id, + department.Name, + Employee: employee) + ); - foreach ((long Id, string Name, Employee Employee) item in items) - { - Console.WriteLine(item.Name); - Console.WriteLine("\t" + item.Employee); - } - //... - #endregion INCLUDE + foreach ((long Id, string Name, Employee Employee) item in items) + { + Console.WriteLine(item.Name); + Console.WriteLine("\t" + item.Employee); } + //... + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.21.GroupingItemsTogetherUsingSystem.Linq.Enumerable.GroupBy.cs b/src/Chapter15/Listing15.21.GroupingItemsTogetherUsingSystem.Linq.Enumerable.GroupBy.cs index bc3cfd87d..5e6105eb9 100644 --- a/src/Chapter15/Listing15.21.GroupingItemsTogetherUsingSystem.Linq.Enumerable.GroupBy.cs +++ b/src/Chapter15/Listing15.21.GroupingItemsTogetherUsingSystem.Linq.Enumerable.GroupBy.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_21; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - IEnumerable employees = CorporateData.Employees; + #endregion EXCLUDE + IEnumerable employees = CorporateData.Employees; - IEnumerable> groupedEmployees = - employees.GroupBy((employee) => employee.DepartmentId); + IEnumerable> groupedEmployees = + employees.GroupBy((employee) => employee.DepartmentId); - foreach(IGrouping employeeGroup in - groupedEmployees) + foreach(IGrouping employeeGroup in + groupedEmployees) + { + Console.WriteLine(); + foreach(Employee employee in employeeGroup) { - Console.WriteLine(); - foreach(Employee employee in employeeGroup) - { - Console.WriteLine(employee); - } - Console.WriteLine( - "\tCount: " + employeeGroup.Count()); + Console.WriteLine(employee); } - //... - #endregion INCLUDE + Console.WriteLine( + "\tCount: " + employeeGroup.Count()); } + //... + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.22.CreatingAChildCollectionWithSystem.Linq.Enumerable.GroupJoin.cs b/src/Chapter15/Listing15.22.CreatingAChildCollectionWithSystem.Linq.Enumerable.GroupJoin.cs index 37f03f4e3..8adab35e9 100644 --- a/src/Chapter15/Listing15.22.CreatingAChildCollectionWithSystem.Linq.Enumerable.GroupJoin.cs +++ b/src/Chapter15/Listing15.22.CreatingAChildCollectionWithSystem.Linq.Enumerable.GroupJoin.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_22 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_22; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - Department[] departments = CorporateData.Departments; - Employee[] employees = CorporateData.Employees; + #endregion EXCLUDE + Department[] departments = CorporateData.Departments; + Employee[] employees = CorporateData.Employees; - IEnumerable<(long Id, string Name, IEnumerable Employees)> items = - departments.GroupJoin( - employees, - department => department.Id, - employee => employee.DepartmentId, - (department, departmentEmployees) => ( - department.Id, - department.Name, - departmentEmployees - )); + IEnumerable<(long Id, string Name, IEnumerable Employees)> items = + departments.GroupJoin( + employees, + department => department.Id, + employee => employee.DepartmentId, + (department, departmentEmployees) => ( + department.Id, + department.Name, + departmentEmployees + )); - foreach ( - (_, string name, IEnumerable employeeCollection) in items) + foreach ( + (_, string name, IEnumerable employeeCollection) in items) + { + Console.WriteLine(name); + foreach (Employee employee in employeeCollection) { - Console.WriteLine(name); - foreach (Employee employee in employeeCollection) - { - Console.WriteLine("\t" + employee); - } + Console.WriteLine("\t" + employee); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.23.ImplementingAnOuterJoinUsingGroupJoinWithSelectMany.cs b/src/Chapter15/Listing15.23.ImplementingAnOuterJoinUsingGroupJoinWithSelectMany.cs index 7b94d1f63..325dfd3cb 100644 --- a/src/Chapter15/Listing15.23.ImplementingAnOuterJoinUsingGroupJoinWithSelectMany.cs +++ b/src/Chapter15/Listing15.23.ImplementingAnOuterJoinUsingGroupJoinWithSelectMany.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_23 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - #region INCLUDE - using System; - using System.Linq; - #region EXCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_23; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; +#region INCLUDE +using System; +using System.Linq; +#region EXCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - Department[] departments = CorporateData.Departments; - Employee[] employees = CorporateData.Employees; + #endregion EXCLUDE + Department[] departments = CorporateData.Departments; + Employee[] employees = CorporateData.Employees; - var items = departments.GroupJoin( - employees, - department => department.Id, - employee => employee.DepartmentId, - (department, departmentEmployees) => new + var items = departments.GroupJoin( + employees, + department => department.Id, + employee => employee.DepartmentId, + (department, departmentEmployees) => new + { + department.Id, + department.Name, + Employees = departmentEmployees + }).SelectMany( + departmentRecord => + departmentRecord.Employees.DefaultIfEmpty(), + (departmentRecord, employee) => new { - department.Id, - department.Name, - Employees = departmentEmployees - }).SelectMany( - departmentRecord => - departmentRecord.Employees.DefaultIfEmpty(), - (departmentRecord, employee) => new - { - departmentRecord.Id, - departmentRecord.Name, - departmentRecord.Employees - }).Distinct(); + departmentRecord.Id, + departmentRecord.Name, + departmentRecord.Employees + }).Distinct(); - foreach (var item in items) + foreach (var item in items) + { + Console.WriteLine(item.Name); + foreach (Employee employee in item.Employees) { - Console.WriteLine(item.Name); - foreach (Employee employee in item.Employees) - { - Console.WriteLine("\t" + employee); - } + Console.WriteLine("\t" + employee); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } } diff --git a/src/Chapter15/Listing15.24.CallingSelectMany.cs b/src/Chapter15/Listing15.24.CallingSelectMany.cs index f8b61b268..c64995631 100644 --- a/src/Chapter15/Listing15.24.CallingSelectMany.cs +++ b/src/Chapter15/Listing15.24.CallingSelectMany.cs @@ -1,71 +1,70 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_24 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_24; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() + #endregion EXCLUDE + (string Team, string[] Players) + [] worldCup2006Finalists = new[] { - #endregion EXCLUDE - (string Team, string[] Players) - [] worldCup2006Finalists = new[] - { - ( - TeamName: "France", - Players: new string[] - { - "Fabien Barthez", "Gregory Coupet", - "Mickael Landreau", "Eric Abidal", - "Jean-Alain Boumsong", "Pascal Chimbonda", - "William Gallas", "Gael Givet", - "Willy Sagnol", "Mikael Silvestre", - "Lilian Thuram", "Vikash Dhorasoo", - "Alou Diarra", "Claude Makelele", - "Florent Malouda", "Patrick Vieira", - "Zinedine Zidane", "Djibril Cisse", - "Thierry Henry", "Franck Ribery", - "Louis Saha", "David Trezeguet", - "Sylvain Wiltord", - } - ), - ( - TeamName: "Italy", - Players: new string[] - { - "Gianluigi Buffon", "Angelo Peruzzi", - "Marco Amelia", "Cristian Zaccardo", - "Alessandro Nesta", "Gianluca Zambrotta", - "Fabio Cannavaro", "Marco Materazzi", - "Fabio Grosso", "Massimo Oddo", - "Andrea Barzagli", "Andrea Pirlo", - "Gennaro Gattuso", "Daniele De Rossi", - "Mauro Camoranesi", "Simone Perrotta", - "Simone Barone", "Luca Toni", - "Alessandro Del Piero", "Francesco Totti", - "Alberto Gilardino", "Filippo Inzaghi", - "Vincenzo Iaquinta", - } - ) - }; + ( + TeamName: "France", + Players: new string[] + { + "Fabien Barthez", "Gregory Coupet", + "Mickael Landreau", "Eric Abidal", + "Jean-Alain Boumsong", "Pascal Chimbonda", + "William Gallas", "Gael Givet", + "Willy Sagnol", "Mikael Silvestre", + "Lilian Thuram", "Vikash Dhorasoo", + "Alou Diarra", "Claude Makelele", + "Florent Malouda", "Patrick Vieira", + "Zinedine Zidane", "Djibril Cisse", + "Thierry Henry", "Franck Ribery", + "Louis Saha", "David Trezeguet", + "Sylvain Wiltord", + } + ), + ( + TeamName: "Italy", + Players: new string[] + { + "Gianluigi Buffon", "Angelo Peruzzi", + "Marco Amelia", "Cristian Zaccardo", + "Alessandro Nesta", "Gianluca Zambrotta", + "Fabio Cannavaro", "Marco Materazzi", + "Fabio Grosso", "Massimo Oddo", + "Andrea Barzagli", "Andrea Pirlo", + "Gennaro Gattuso", "Daniele De Rossi", + "Mauro Camoranesi", "Simone Perrotta", + "Simone Barone", "Luca Toni", + "Alessandro Del Piero", "Francesco Totti", + "Alberto Gilardino", "Filippo Inzaghi", + "Vincenzo Iaquinta", + } + ) + }; - IEnumerable players = - worldCup2006Finalists.SelectMany( - team => team.Players); + IEnumerable players = + worldCup2006Finalists.SelectMany( + team => team.Players); - Print(players); - //... - #endregion INCLUDE - } + Print(players); + //... + #endregion INCLUDE + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } } diff --git a/src/Chapter15/Listing15.25.MoreSystem.Linq.EnumerableMethodCalls.cs b/src/Chapter15/Listing15.25.MoreSystem.Linq.EnumerableMethodCalls.cs index b89442cc4..96b618ce4 100644 --- a/src/Chapter15/Listing15.25.MoreSystem.Linq.EnumerableMethodCalls.cs +++ b/src/Chapter15/Listing15.25.MoreSystem.Linq.EnumerableMethodCalls.cs @@ -1,76 +1,75 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_25 -{ - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_25; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - IEnumerable stuff = - new object[] { new object(), 1, 3, 5, 7, 9, - "\"thing\"", Guid.NewGuid() }; - Print("Stuff: {0}", stuff); + IEnumerable stuff = + new object[] { new object(), 1, 3, 5, 7, 9, + "\"thing\"", Guid.NewGuid() }; + Print("Stuff: {0}", stuff); - IEnumerable even = new int[] { 0, 2, 4, 6, 8 }; - Print("Even integers: {0}", even); + IEnumerable even = new int[] { 0, 2, 4, 6, 8 }; + Print("Even integers: {0}", even); - #region HIGHLIGHT - IEnumerable odd = stuff.OfType(); - #endregion HIGHLIGHT - Print("Odd integers: {0}", odd); + #region HIGHLIGHT + IEnumerable odd = stuff.OfType(); + #endregion HIGHLIGHT + Print("Odd integers: {0}", odd); - #region HIGHLIGHT - IEnumerable numbers = even.Union(odd); - #endregion HIGHLIGHT - Print("Union of odd and even: {0}", numbers); + #region HIGHLIGHT + IEnumerable numbers = even.Union(odd); + #endregion HIGHLIGHT + Print("Union of odd and even: {0}", numbers); - #region HIGHLIGHT - Print("Union with even: {0}", numbers.Union(even)); - Print("Concat with odd: {0}", numbers.Concat(odd)); - #endregion HIGHLIGHT - Print("Intersection with even: {0}", - #region HIGHLIGHT - numbers.Intersect(even)); - Print("Distinct: {0}", numbers.Concat(odd).Distinct()); - #endregion HIGHLIGHT + #region HIGHLIGHT + Print("Union with even: {0}", numbers.Union(even)); + Print("Concat with odd: {0}", numbers.Concat(odd)); + #endregion HIGHLIGHT + Print("Intersection with even: {0}", + #region HIGHLIGHT + numbers.Intersect(even)); + Print("Distinct: {0}", numbers.Concat(odd).Distinct()); + #endregion HIGHLIGHT - #region HIGHLIGHT - if (!numbers.SequenceEqual( - numbers.Concat(odd).Distinct())) - #endregion HIGHLIGHT - { - throw new Exception("Unexpectedly unequal"); - } - else - { - Console.WriteLine( - @"Collection ""SequenceEquals""" + - $" {nameof(numbers)}.Concat(odd).Distinct())"); - } - #region HIGHLIGHT - Print("Reverse: {0}", numbers.Reverse()); - Print("Average: {0}", numbers.Average()); - Print("Sum: {0}", numbers.Sum()); - Print("Max: {0}", numbers.Max()); - Print("Min: {0}", numbers.Min()); - #endregion HIGHLIGHT + #region HIGHLIGHT + if (!numbers.SequenceEqual( + numbers.Concat(odd).Distinct())) + #endregion HIGHLIGHT + { + throw new Exception("Unexpectedly unequal"); } - - private static void Print( - string format, IEnumerable items) - where T : notnull => - Console.WriteLine(format, string.Join( - ", ", items)); - #region EXCLUDE - - private static void Print(string format, T item) + else { - Console.WriteLine(format, item); + Console.WriteLine( + @"Collection ""SequenceEquals""" + + $" {nameof(numbers)}.Concat(odd).Distinct())"); } - #endregion EXCLUDE + #region HIGHLIGHT + Print("Reverse: {0}", numbers.Reverse()); + Print("Average: {0}", numbers.Average()); + Print("Sum: {0}", numbers.Sum()); + Print("Max: {0}", numbers.Max()); + Print("Min: {0}", numbers.Min()); + #endregion HIGHLIGHT + } + + private static void Print( + string format, IEnumerable items) + where T : notnull => + Console.WriteLine(format, string.Join( + ", ", items)); + #region EXCLUDE + + private static void Print(string format, T item) + { + Console.WriteLine(format, item); } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.26.ImplicitLocalVariablesWithAnonymousTypes.cs b/src/Chapter15/Listing15.26.ImplicitLocalVariablesWithAnonymousTypes.cs index 401020714..7fa21140f 100644 --- a/src/Chapter15/Listing15.26.ImplicitLocalVariablesWithAnonymousTypes.cs +++ b/src/Chapter15/Listing15.26.ImplicitLocalVariablesWithAnonymousTypes.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_26 -{ - #region INCLUDE - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_26; + +#region INCLUDE +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - #region HIGHLIGHT - var patent1 = - new - { - Title = "Bifocals", - YearOfPublication = "1784" - }; - var patent2 = - new - { - Title = "Phonograph", - YearOfPublication = "1877" - }; - var patent3 = - new - { - patent1.Title, - // Renamed to show property naming - Year = patent1.YearOfPublication - }; - #endregion HIGHLIGHT + #region HIGHLIGHT + var patent1 = + new + { + Title = "Bifocals", + YearOfPublication = "1784" + }; + var patent2 = + new + { + Title = "Phonograph", + YearOfPublication = "1877" + }; + var patent3 = + new + { + patent1.Title, + // Renamed to show property naming + Year = patent1.YearOfPublication + }; + #endregion HIGHLIGHT - Console.WriteLine( - $"{ patent1.Title } ({ patent1.YearOfPublication })"); - Console.WriteLine( - $"{ patent2.Title } ({ patent2.YearOfPublication })"); + Console.WriteLine( + $"{ patent1.Title } ({ patent1.YearOfPublication })"); + Console.WriteLine( + $"{ patent2.Title } ({ patent2.YearOfPublication })"); - Console.WriteLine(); - Console.WriteLine(patent1); - Console.WriteLine(patent2); + Console.WriteLine(); + Console.WriteLine(patent1); + Console.WriteLine(patent2); - Console.WriteLine(); - Console.WriteLine(patent3); - } + Console.WriteLine(); + Console.WriteLine(patent3); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.27.ProjectionToAnAnonymousType.cs b/src/Chapter15/Listing15.27.ProjectionToAnAnonymousType.cs index 195e68515..7c420529d 100644 --- a/src/Chapter15/Listing15.27.ProjectionToAnAnonymousType.cs +++ b/src/Chapter15/Listing15.27.ProjectionToAnAnonymousType.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_27 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_27; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +public class Program { - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - public class Program + public static void Main() { - public static void Main() - { - string rootDirectory = Directory.GetCurrentDirectory(); - string searchPattern = "*"; - #region INCLUDE - //... - IEnumerable fileList = Directory.EnumerateFiles( - rootDirectory, searchPattern); - #region HIGHLIGHT - var items = fileList.Select( - file => + string rootDirectory = Directory.GetCurrentDirectory(); + string searchPattern = "*"; + #region INCLUDE + //... + IEnumerable fileList = Directory.EnumerateFiles( + rootDirectory, searchPattern); + #region HIGHLIGHT + var items = fileList.Select( + file => + { + FileInfo fileInfo = new FileInfo(file); + return new { - FileInfo fileInfo = new FileInfo(file); - return new - { - FileName = fileInfo.Name, - Size = fileInfo.Length - }; - }); - #endregion HIGHLIGHT - //... - #endregion INCLUDE + FileName = fileInfo.Name, + Size = fileInfo.Length + }; + }); + #endregion HIGHLIGHT + //... + #endregion INCLUDE - Print(items); - } + Print(items); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } } diff --git a/src/Chapter15/Listing15.28.TypeSafetyAndImmutabilityOfAnonymousTypes.cs b/src/Chapter15/Listing15.28.TypeSafetyAndImmutabilityOfAnonymousTypes.cs index 3ddb917c9..f6b339f96 100644 --- a/src/Chapter15/Listing15.28.TypeSafetyAndImmutabilityOfAnonymousTypes.cs +++ b/src/Chapter15/Listing15.28.TypeSafetyAndImmutabilityOfAnonymousTypes.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_28 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_28; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - var patent1 = - new - { - Title = "Bifocals", - YearOfPublication = "1784" - }; + var patent1 = + new + { + Title = "Bifocals", + YearOfPublication = "1784" + }; - var patent2 = - new - { - YearOfPublication = "1877", - Title = "Phonograph" - }; + var patent2 = + new + { + YearOfPublication = "1877", + Title = "Phonograph" + }; - var patent3 = - new - { - patent1.Title, - Year = patent1.YearOfPublication - }; + var patent3 = + new + { + patent1.Title, + Year = patent1.YearOfPublication + }; - // ERROR: Cannot implicitly convert type - // 'AnonymousType#1' to 'AnonymousType#2' - //patent1 = patent2; //won't compile if uncommented - // ERROR: Cannot implicitly convert type - // 'AnonymousType#1' to 'AnonymousType#3' - //patent1 = patent3; //won't compile if uncommented + // ERROR: Cannot implicitly convert type + // 'AnonymousType#1' to 'AnonymousType#2' + //patent1 = patent2; //won't compile if uncommented + // ERROR: Cannot implicitly convert type + // 'AnonymousType#1' to 'AnonymousType#3' + //patent1 = patent3; //won't compile if uncommented - // ERROR: Property or indexer 'AnonymousType#1.Title' - // cannot be assigned to -- it is read-only' - //patent1.Title = "Swiss Cheese"; - //won't compile if uncommented - } + // ERROR: Property or indexer 'AnonymousType#1.Title' + // cannot be assigned to -- it is read-only' + //patent1.Title = "Swiss Cheese"; + //won't compile if uncommented } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/Listing15.29.InitializingAnonymousTypeArrays.cs b/src/Chapter15/Listing15.29.InitializingAnonymousTypeArrays.cs index 09dcb263d..25fff41f4 100644 --- a/src/Chapter15/Listing15.29.InitializingAnonymousTypeArrays.cs +++ b/src/Chapter15/Listing15.29.InitializingAnonymousTypeArrays.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_29 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15_29; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + var worldCup2006Finalists = new[] { - var worldCup2006Finalists = new[] + new { - new + TeamName = "France", + Players = new string[] { - TeamName = "France", - Players = new string[] - { - "Fabien Barthez", "Gregory Coupet", - "Mickael Landreau", "Eric Abidal", - // ... - } - }, - new + "Fabien Barthez", "Gregory Coupet", + "Mickael Landreau", "Eric Abidal", + // ... + } + }, + new + { + TeamName = "Italy", + Players = new string[] { - TeamName = "Italy", - Players = new string[] - { - "Gianluigi Buffon", "Angelo Peruzzi", - "Marco Amelia", "Cristian Zaccardo", - // ... - } + "Gianluigi Buffon", "Angelo Peruzzi", + "Marco Amelia", "Cristian Zaccardo", + // ... } - }; + } + }; - Print(worldCup2006Finalists); - } + Print(worldCup2006Finalists); + } - private static void Print(IEnumerable items) + private static void Print(IEnumerable items) + { + foreach(T item in items) { - foreach(T item in items) - { - Console.WriteLine(item); - } + Console.WriteLine(item); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter15/PatentData.cs b/src/Chapter15/PatentData.cs index 8b68dcf9a..e8037b69b 100644 --- a/src/Chapter15/PatentData.cs +++ b/src/Chapter15/PatentData.cs @@ -1,97 +1,96 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15 -{ - public class Patent - { - // Title of the published application - public string Title { get; } - - // The date the application was officially published - public string YearOfPublication { get; } +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter15.Listing15; - // A unique number assigned to published applications - public string? ApplicationNumber { get; set; } +public class Patent +{ + // Title of the published application + public string Title { get; } - public long[] InventorIds { get; } + // The date the application was officially published + public string YearOfPublication { get; } - public Patent( - string title, string yearOfPublication, long[] inventorIds) - { - Title = title ?? throw new ArgumentNullException(nameof(title)); - YearOfPublication = yearOfPublication ?? - throw new ArgumentNullException(nameof(yearOfPublication)); - InventorIds = inventorIds ?? - throw new ArgumentNullException(nameof(inventorIds)); - } + // A unique number assigned to published applications + public string? ApplicationNumber { get; set; } - public override string ToString() - { - return $"{ Title } ({ YearOfPublication })"; - } + public long[] InventorIds { get; } + public Patent( + string title, string yearOfPublication, long[] inventorIds) + { + Title = title ?? throw new ArgumentNullException(nameof(title)); + YearOfPublication = yearOfPublication ?? + throw new ArgumentNullException(nameof(yearOfPublication)); + InventorIds = inventorIds ?? + throw new ArgumentNullException(nameof(inventorIds)); } - public class Inventor + public override string ToString() { - public long Id { get; } - public string Name { get; } - public string City { get; } - public string State { get; } - public string Country { get; } + return $"{ Title } ({ YearOfPublication })"; + } - public Inventor( - string name, string city, string state, string country, int id) - { - Name = name ?? throw new ArgumentNullException(nameof(name)); - City = city ?? throw new ArgumentNullException(nameof(city)); - State = state ?? throw new ArgumentNullException(nameof(state)); - Country = country ?? throw new ArgumentNullException(nameof(country)); - Id = id; - } +} - public override string ToString() - { - return $"{ Name } ({ City }, { State })"; - } +public class Inventor +{ + public long Id { get; } + public string Name { get; } + public string City { get; } + public string State { get; } + public string Country { get; } + public Inventor( + string name, string city, string state, string country, int id) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + City = city ?? throw new ArgumentNullException(nameof(city)); + State = state ?? throw new ArgumentNullException(nameof(state)); + Country = country ?? throw new ArgumentNullException(nameof(country)); + Id = id; } - public static class PatentData + public override string ToString() { - public static readonly Inventor[] Inventors = new Inventor[] - { - new Inventor( - "Benjamin Franklin", "Philadelphia", - "PA", "USA", 1), - new Inventor( - "Orville Wright", "Kitty Hawk", - "NC", "USA", 2), - new Inventor( - "Wilbur Wright", "Kitty Hawk", - "NC", "USA", 3), - new Inventor( - "Samuel Morse", "New York", - "NY", "USA", 4), - new Inventor( - "George Stephenson", "Wylam", - "Northumberland", "UK", 5), - new Inventor( - "John Michaelis", "Chicago", - "IL", "USA", 6), - new Inventor( - "Mary Phelps Jacob", "New York", - "NY", "USA", 7) - }; - - public static readonly Patent[] Patents = new Patent[] - { - new Patent("Bifocals","1784", inventorIds: new long[] { 1 }), - new Patent("Phonograph", "1877", inventorIds: new long[] { 1 }), - new Patent("Kinetoscope", "1888", inventorIds: new long[] { 1 }), - new Patent("Electrical Telegraph", "1837", inventorIds: new long[] { 4 }), - new Patent("Flying Machine", "1903", inventorIds: new long[] { 2, 3 }), - new Patent("Steam Locomotive", "1815", inventorIds: new long[] { 5 }), - new Patent("Droplet Deposition Apparatus", "1989", inventorIds: new long[] { 6 }), - new Patent("Backless Brassiere", "1914", inventorIds: new long[] { 7 }) - }; + return $"{ Name } ({ City }, { State })"; } + +} + +public static class PatentData +{ + public static readonly Inventor[] Inventors = new Inventor[] + { + new Inventor( + "Benjamin Franklin", "Philadelphia", + "PA", "USA", 1), + new Inventor( + "Orville Wright", "Kitty Hawk", + "NC", "USA", 2), + new Inventor( + "Wilbur Wright", "Kitty Hawk", + "NC", "USA", 3), + new Inventor( + "Samuel Morse", "New York", + "NY", "USA", 4), + new Inventor( + "George Stephenson", "Wylam", + "Northumberland", "UK", 5), + new Inventor( + "John Michaelis", "Chicago", + "IL", "USA", 6), + new Inventor( + "Mary Phelps Jacob", "New York", + "NY", "USA", 7) + }; + + public static readonly Patent[] Patents = new Patent[] + { + new Patent("Bifocals","1784", inventorIds: new long[] { 1 }), + new Patent("Phonograph", "1877", inventorIds: new long[] { 1 }), + new Patent("Kinetoscope", "1888", inventorIds: new long[] { 1 }), + new Patent("Electrical Telegraph", "1837", inventorIds: new long[] { 4 }), + new Patent("Flying Machine", "1903", inventorIds: new long[] { 2, 3 }), + new Patent("Steam Locomotive", "1815", inventorIds: new long[] { 5 }), + new Patent("Droplet Deposition Apparatus", "1989", inventorIds: new long[] { 6 }), + new Patent("Backless Brassiere", "1914", inventorIds: new long[] { 7 }) + }; } diff --git a/src/Chapter16/Listing16.02.ProjectingUsingQueryExpressions.cs b/src/Chapter16/Listing16.02.ProjectingUsingQueryExpressions.cs index dd8f22e03..72556bcb5 100644 --- a/src/Chapter16/Listing16.02.ProjectingUsingQueryExpressions.cs +++ b/src/Chapter16/Listing16.02.ProjectingUsingQueryExpressions.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_02; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - List1(Directory.GetCurrentDirectory(), "*"); - } - #endregion EXCLUDE - public static void List1 - (string rootDirectory, string searchPattern) - { - #region HIGHLIGHT - IEnumerable fileNames = Directory.GetFiles( - rootDirectory, searchPattern); + List1(Directory.GetCurrentDirectory(), "*"); + } + #endregion EXCLUDE + public static void List1 + (string rootDirectory, string searchPattern) + { + #region HIGHLIGHT + IEnumerable fileNames = Directory.GetFiles( + rootDirectory, searchPattern); - IEnumerable fileInfos = - from fileName in fileNames - select new FileInfo(fileName); - #endregion HIGHLIGHT + IEnumerable fileInfos = + from fileName in fileNames + select new FileInfo(fileName); + #endregion HIGHLIGHT - foreach (FileInfo fileInfo in fileInfos) - { - Console.WriteLine( - $@".{ fileInfo.Name } ({ - fileInfo.LastWriteTime })"); - } + foreach (FileInfo fileInfo in fileInfos) + { + Console.WriteLine( + $@".{ fileInfo.Name } ({ + fileInfo.LastWriteTime })"); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter16/Listing16.03.TuplesWithinQueryExpressions.cs b/src/Chapter16/Listing16.03.TuplesWithinQueryExpressions.cs index 91abcffde..9cf2dfd0b 100644 --- a/src/Chapter16/Listing16.03.TuplesWithinQueryExpressions.cs +++ b/src/Chapter16/Listing16.03.TuplesWithinQueryExpressions.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_03; + +#region INCLUDE +using System; +using System.IO; +using System.Linq; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.IO; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - List2(Directory.GetCurrentDirectory(), "*"); - } - #endregion EXCLUDE - public static void List2 - (string rootDirectory, string searchPattern) + List2(Directory.GetCurrentDirectory(), "*"); + } + #endregion EXCLUDE + public static void List2 + (string rootDirectory, string searchPattern) + { + #region HIGHLIGHT + var fileNames = Directory.EnumerateFiles( + rootDirectory, searchPattern); + var fileResults = + from fileName in fileNames + select + ( + Name: fileName, + LastWriteTime: File.GetLastWriteTime(fileName) + ); + #endregion HIGHLIGHT + + foreach (var fileResult in fileResults) { + Console.WriteLine( #region HIGHLIGHT - var fileNames = Directory.EnumerateFiles( - rootDirectory, searchPattern); - var fileResults = - from fileName in fileNames - select - ( - Name: fileName, - LastWriteTime: File.GetLastWriteTime(fileName) - ); + $@"{ fileResult.Name } ({ + fileResult.LastWriteTime })"); #endregion HIGHLIGHT - - foreach (var fileResult in fileResults) - { - Console.WriteLine( - #region HIGHLIGHT - $@"{ fileResult.Name } ({ - fileResult.LastWriteTime })"); - #endregion HIGHLIGHT - } } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter16/Listing16.04.DeferredExecutionAndQueryExpressions1.cs b/src/Chapter16/Listing16.04.DeferredExecutionAndQueryExpressions1.cs index 5e096bee6..5d7d9a188 100644 --- a/src/Chapter16/Listing16.04.DeferredExecutionAndQueryExpressions1.cs +++ b/src/Chapter16/Listing16.04.DeferredExecutionAndQueryExpressions1.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_04; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() + { + ShowContextualKeywords2(); + } + #endregion EXCLUDE + private static void ShowContextualKeywords2() { - public static void Main() + IEnumerable selection = from word in CSharp.Keywords + where IsKeyword(word) + select word; + Console.WriteLine("Query created."); + foreach(string keyword in selection) { - ShowContextualKeywords2(); + // No space output here + Console.Write(keyword); } - #endregion EXCLUDE - private static void ShowContextualKeywords2() + } + + // The side effect of console output is included + // in the predicate to demonstrate deferred execution; + // predicates with side effects are a poor practice in + // production code + private static bool IsKeyword(string word) + { + if(word.Contains('*')) { - IEnumerable selection = from word in CSharp.Keywords - where IsKeyword(word) - select word; - Console.WriteLine("Query created."); - foreach(string keyword in selection) - { - // No space output here - Console.Write(keyword); - } + Console.Write(" "); + return true; } - - // The side effect of console output is included - // in the predicate to demonstrate deferred execution; - // predicates with side effects are a poor practice in - // production code - private static bool IsKeyword(string word) + else { - if(word.Contains('*')) - { - Console.Write(" "); - return true; - } - else - { - return false; - } + return false; } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } \ No newline at end of file diff --git a/src/Chapter16/Listing16.05.DeferredExecutionAndQueryExpressions2.cs b/src/Chapter16/Listing16.05.DeferredExecutionAndQueryExpressions2.cs index 1e0332d8e..60e2fc254 100644 --- a/src/Chapter16/Listing16.05.DeferredExecutionAndQueryExpressions2.cs +++ b/src/Chapter16/Listing16.05.DeferredExecutionAndQueryExpressions2.cs @@ -1,67 +1,66 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_05; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() + { + CountContextualKeywords(); + } + #endregion EXCLUDE + private static void CountContextualKeywords() { - public static void Main() + int delegateInvocations = 0; + string func(string text) { - CountContextualKeywords(); + delegateInvocations++; + return text; } - #endregion EXCLUDE - private static void CountContextualKeywords() - { - int delegateInvocations = 0; - string func(string text) - { - delegateInvocations++; - return text; - } - IEnumerable selection = - from keyword in CSharp.Keywords - where keyword.Contains('*') - select func(keyword); + IEnumerable selection = + from keyword in CSharp.Keywords + where keyword.Contains('*') + select func(keyword); - Console.WriteLine( - $"1. delegateInvocations={ delegateInvocations }"); + Console.WriteLine( + $"1. delegateInvocations={ delegateInvocations }"); - // Executing count should invoke func once for - // each item selected - Console.WriteLine( - $"2. Contextual keyword count={ selection.Count() }"); + // Executing count should invoke func once for + // each item selected + Console.WriteLine( + $"2. Contextual keyword count={ selection.Count() }"); - Console.WriteLine( - $"3. delegateInvocations={ delegateInvocations }"); + Console.WriteLine( + $"3. delegateInvocations={ delegateInvocations }"); - // Executing count should invoke func once for - // each item selected - Console.WriteLine( - $"4. Contextual keyword count={ selection.Count() }"); + // Executing count should invoke func once for + // each item selected + Console.WriteLine( + $"4. Contextual keyword count={ selection.Count() }"); - Console.WriteLine( - $"5. delegateInvocations={ delegateInvocations }"); + Console.WriteLine( + $"5. delegateInvocations={ delegateInvocations }"); - // Cache the value so future counts will not trigger - // another invocation of the query - List selectionCache = selection.ToList(); + // Cache the value so future counts will not trigger + // another invocation of the query + List selectionCache = selection.ToList(); - Console.WriteLine( - $"6. delegateInvocations={ delegateInvocations }"); + Console.WriteLine( + $"6. delegateInvocations={ delegateInvocations }"); - // Retrieve the count from the cached collection - Console.WriteLine( - $"7. selectionCache count={ selectionCache.Count }"); + // Retrieve the count from the cached collection + Console.WriteLine( + $"7. selectionCache count={ selectionCache.Count }"); - Console.WriteLine( - $"8. delegateInvocations={ delegateInvocations }"); - } - //... - #endregion INCLUDE + Console.WriteLine( + $"8. delegateInvocations={ delegateInvocations }"); } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.06.AnonymousTypesWithinQueryExpressions.cs b/src/Chapter16/Listing16.06.AnonymousTypesWithinQueryExpressions.cs index 75bda9deb..9a7b3dc97 100644 --- a/src/Chapter16/Listing16.06.AnonymousTypesWithinQueryExpressions.cs +++ b/src/Chapter16/Listing16.06.AnonymousTypesWithinQueryExpressions.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_06; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - FindMonthOldFiles(Directory.GetCurrentDirectory(), "*"); - } - #endregion EXCLUDE - public static void FindMonthOldFiles( - string rootDirectory, string searchPattern) - { - IEnumerable files = - from fileName in Directory.EnumerateFiles( - rootDirectory, searchPattern) - #region HIGHLIGHT - where File.GetLastWriteTime(fileName) < - DateTime.Now.AddMonths(-1) - #endregion HIGHLIGHT - select new FileInfo(fileName); + FindMonthOldFiles(Directory.GetCurrentDirectory(), "*"); + } + #endregion EXCLUDE + public static void FindMonthOldFiles( + string rootDirectory, string searchPattern) + { + IEnumerable files = + from fileName in Directory.EnumerateFiles( + rootDirectory, searchPattern) + #region HIGHLIGHT + where File.GetLastWriteTime(fileName) < + DateTime.Now.AddMonths(-1) + #endregion HIGHLIGHT + select new FileInfo(fileName); - foreach(FileInfo file in files) - { - // As a simplification, the current directory is - // assumed to be a subdirectory of - // rootDirectory - string relativePath = file.FullName.Substring( - Directory.GetCurrentDirectory().Length); - Console.WriteLine( - $".{ relativePath } ({ file.LastWriteTime })"); - } + foreach(FileInfo file in files) + { + // As a simplification, the current directory is + // assumed to be a subdirectory of + // rootDirectory + string relativePath = file.FullName.Substring( + Directory.GetCurrentDirectory().Length); + Console.WriteLine( + $".{ relativePath } ({ file.LastWriteTime })"); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.07.SortingUsingAQueryExpressionWithAnOrderbyClause.cs b/src/Chapter16/Listing16.07.SortingUsingAQueryExpressionWithAnOrderbyClause.cs index 397ca7b25..861178809 100644 --- a/src/Chapter16/Listing16.07.SortingUsingAQueryExpressionWithAnOrderbyClause.cs +++ b/src/Chapter16/Listing16.07.SortingUsingAQueryExpressionWithAnOrderbyClause.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_07; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - using System.IO; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - ListByFileSize1(Directory.GetCurrentDirectory(), "*"); - } - #endregion EXCLUDE - public static void ListByFileSize1( - string rootDirectory, string searchPattern) - { - IEnumerable fileNames = - from fileName in Directory.EnumerateFiles( - rootDirectory, searchPattern) - #region HIGHLIGHT - orderby (new FileInfo(fileName)).Length descending, - fileName - #endregion HIGHLIGHT - select fileName; + ListByFileSize1(Directory.GetCurrentDirectory(), "*"); + } + #endregion EXCLUDE + public static void ListByFileSize1( + string rootDirectory, string searchPattern) + { + IEnumerable fileNames = + from fileName in Directory.EnumerateFiles( + rootDirectory, searchPattern) + #region HIGHLIGHT + orderby (new FileInfo(fileName)).Length descending, + fileName + #endregion HIGHLIGHT + select fileName; - foreach(string fileName in fileNames) - { - Console.WriteLine(fileName); - } + foreach(string fileName in fileNames) + { + Console.WriteLine(fileName); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.08.ProjectingAFileInfoCollectionAndSortingByFileSize.cs b/src/Chapter16/Listing16.08.ProjectingAFileInfoCollectionAndSortingByFileSize.cs index c488b0c91..ec689d901 100644 --- a/src/Chapter16/Listing16.08.ProjectingAFileInfoCollectionAndSortingByFileSize.cs +++ b/src/Chapter16/Listing16.08.ProjectingAFileInfoCollectionAndSortingByFileSize.cs @@ -1,41 +1,40 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_08; + +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - using System.IO; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - ListByFileSize2(Directory.GetCurrentDirectory(), "*"); - } - #endregion EXCLUDE - public static void ListByFileSize2( - string rootDirectory, string searchPattern) - { - IEnumerable files = - from fileName in Directory.EnumerateFiles( - rootDirectory, searchPattern) - #region HIGHLIGHT - orderby new FileInfo(fileName).Length, fileName - select new FileInfo(fileName); - #endregion HIGHLIGHT + ListByFileSize2(Directory.GetCurrentDirectory(), "*"); + } + #endregion EXCLUDE + public static void ListByFileSize2( + string rootDirectory, string searchPattern) + { + IEnumerable files = + from fileName in Directory.EnumerateFiles( + rootDirectory, searchPattern) + #region HIGHLIGHT + orderby new FileInfo(fileName).Length, fileName + select new FileInfo(fileName); + #endregion HIGHLIGHT - foreach (FileInfo file in files) - { - // As a simplification, the current directory - // is assumed to be a subdirectory of - // rootDirectory - string relativePath = file.FullName.Substring( - Directory.GetCurrentDirectory().Length); - Console.WriteLine( - $".{ relativePath }({ file.Length })"); - } + foreach (FileInfo file in files) + { + // As a simplification, the current directory + // is assumed to be a subdirectory of + // rootDirectory + string relativePath = file.FullName.Substring( + Directory.GetCurrentDirectory().Length); + Console.WriteLine( + $".{ relativePath }({ file.Length })"); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.09.OrderingTheResultsInAQueryExpression.cs b/src/Chapter16/Listing16.09.OrderingTheResultsInAQueryExpression.cs index c03a20cc3..60d5317c9 100644 --- a/src/Chapter16/Listing16.09.OrderingTheResultsInAQueryExpression.cs +++ b/src/Chapter16/Listing16.09.OrderingTheResultsInAQueryExpression.cs @@ -1,44 +1,43 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_09 -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.IO; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_09; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - ListByFileSize3(Directory.GetCurrentDirectory(), "*"); - } + ListByFileSize3(Directory.GetCurrentDirectory(), "*"); + } - static void ListByFileSize3( - string rootDirectory, string searchPattern) - { - #region INCLUDE - //... - IEnumerable files = - from fileName in Directory.EnumerateFiles( - rootDirectory, searchPattern) - #region HIGHLIGHT - let file = new FileInfo(fileName) - orderby file.Length, fileName - select file; - #endregion HIGHLIGHT - //... - #endregion INCLUDE + static void ListByFileSize3( + string rootDirectory, string searchPattern) + { + #region INCLUDE + //... + IEnumerable files = + from fileName in Directory.EnumerateFiles( + rootDirectory, searchPattern) + #region HIGHLIGHT + let file = new FileInfo(fileName) + orderby file.Length, fileName + select file; + #endregion HIGHLIGHT + //... + #endregion INCLUDE - foreach (FileInfo file in files) - { - // As simplification, current directory is - // assumed to be a subdirectory of - // rootDirectory - string relativePath = file.FullName.Substring( - Directory.GetCurrentDirectory().Length); - Console.WriteLine( - $".{ relativePath }({ file.Length })" ); - } + foreach (FileInfo file in files) + { + // As simplification, current directory is + // assumed to be a subdirectory of + // rootDirectory + string relativePath = file.FullName.Substring( + Directory.GetCurrentDirectory().Length); + Console.WriteLine( + $".{ relativePath }({ file.Length })" ); } } } diff --git a/src/Chapter16/Listing16.10.GroupingTogetherQueryResults.cs b/src/Chapter16/Listing16.10.GroupingTogetherQueryResults.cs index 61621f0d5..39285304c 100644 --- a/src/Chapter16/Listing16.10.GroupingTogetherQueryResults.cs +++ b/src/Chapter16/Listing16.10.GroupingTogetherQueryResults.cs @@ -1,40 +1,39 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_10 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_10; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - GroupKeywords1(); - } - #endregion EXCLUDE - private static void GroupKeywords1() - { - IEnumerable> selection = - from word in CSharp.Keywords - group word by word.Contains('*'); + GroupKeywords1(); + } + #endregion EXCLUDE + private static void GroupKeywords1() + { + IEnumerable> selection = + from word in CSharp.Keywords + group word by word.Contains('*'); - foreach(IGrouping wordGroup - in selection) + foreach(IGrouping wordGroup + in selection) + { + Console.WriteLine(Environment.NewLine + "{0}:", + wordGroup.Key ? + "Contextual Keywords" : "Keywords"); + foreach(string keyword in wordGroup) { - Console.WriteLine(Environment.NewLine + "{0}:", - wordGroup.Key ? - "Contextual Keywords" : "Keywords"); - foreach(string keyword in wordGroup) - { - Console.Write(" " + - (wordGroup.Key ? - keyword.Replace("*", null) : keyword)); - } + Console.Write(" " + + (wordGroup.Key ? + keyword.Replace("*", null) : keyword)); } } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.11.SelectingTupleFollowingTheGroupbyClause.cs b/src/Chapter16/Listing16.11.SelectingTupleFollowingTheGroupbyClause.cs index c98c4ae54..8b6b13082 100644 --- a/src/Chapter16/Listing16.11.SelectingTupleFollowingTheGroupbyClause.cs +++ b/src/Chapter16/Listing16.11.SelectingTupleFollowingTheGroupbyClause.cs @@ -1,52 +1,51 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_11; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - GroupKeywords1(); - } - #endregion EXCLUDE - private static void GroupKeywords1() + GroupKeywords1(); + } + #endregion EXCLUDE + private static void GroupKeywords1() + { + #region HIGHLIGHT + IEnumerable> keywordGroups = + from word in CSharp.Keywords + group word by word.Contains('*'); + + IEnumerable<(bool IsContextualKeyword, + IGrouping Items)> selection = + from groups in keywordGroups + select + ( + IsContextualKeyword: groups.Key, + Items: groups + ); + #endregion HIGHLIGHT + + foreach ( + (bool isContextualKeyword, IGrouping items) + in selection) { - #region HIGHLIGHT - IEnumerable> keywordGroups = - from word in CSharp.Keywords - group word by word.Contains('*'); - IEnumerable<(bool IsContextualKeyword, - IGrouping Items)> selection = - from groups in keywordGroups - select - ( - IsContextualKeyword: groups.Key, - Items: groups - ); + Console.WriteLine(Environment.NewLine + "{0}:", + isContextualKeyword ? + "Contextual Keywords" : "Keywords"); + #region HIGHLIGHT + foreach (string keyword in items) #endregion HIGHLIGHT - - foreach ( - (bool isContextualKeyword, IGrouping items) - in selection) { - - Console.WriteLine(Environment.NewLine + "{0}:", - isContextualKeyword ? - "Contextual Keywords" : "Keywords"); - #region HIGHLIGHT - foreach (string keyword in items) - #endregion HIGHLIGHT - { - Console.Write(" " + keyword.Replace("*", null)); - } + Console.Write(" " + keyword.Replace("*", null)); } } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.12.SelectingWithoutTheQueryContinuation.cs b/src/Chapter16/Listing16.12.SelectingWithoutTheQueryContinuation.cs index 03262744b..39f4203e2 100644 --- a/src/Chapter16/Listing16.12.SelectingWithoutTheQueryContinuation.cs +++ b/src/Chapter16/Listing16.12.SelectingWithoutTheQueryContinuation.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_12; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.Linq; +#region EXCLUDE +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.Linq; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - GroupKeywords1(); - } - #endregion EXCLUDE - private static void GroupKeywords1() - { - IEnumerable<(bool IsContextualKeyword, - IGrouping Items)> selection = - from word in CSharp.Keywords - #region HIGHLIGHT - group word by word.Contains('*') - into groups - select - ( - IsContextualKeyword: groups.Key, - Items: groups - ); - #endregion HIGHLIGHT - #region EXCLUDE + GroupKeywords1(); + } + #endregion EXCLUDE + private static void GroupKeywords1() + { + IEnumerable<(bool IsContextualKeyword, + IGrouping Items)> selection = + from word in CSharp.Keywords + #region HIGHLIGHT + group word by word.Contains('*') + into groups + select + ( + IsContextualKeyword: groups.Key, + Items: groups + ); + #endregion HIGHLIGHT + #region EXCLUDE - foreach ((bool isContextualKeyword, IGrouping items) in selection) + foreach ((bool isContextualKeyword, IGrouping items) in selection) + { + Console.WriteLine(Environment.NewLine + "{0}:", + isContextualKeyword ? + "Contextual Keywords" : "Keywords"); + foreach(var keyword in items) { - Console.WriteLine(Environment.NewLine + "{0}:", - isContextualKeyword ? - "Contextual Keywords" : "Keywords"); - foreach(var keyword in items) - { - Console.Write(" " + - keyword.Replace("*", null)); - } + Console.Write(" " + + keyword.Replace("*", null)); } - #endregion EXCLUDE } - //... - #endregion INCLUDE + #endregion EXCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.13.MultipleSelection.cs b/src/Chapter16/Listing16.13.MultipleSelection.cs index 1fa0d5f5d..a7ec46f41 100644 --- a/src/Chapter16/Listing16.13.MultipleSelection.cs +++ b/src/Chapter16/Listing16.13.MultipleSelection.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_13; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +using System; +using System.Linq; + +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - using System; - using System.Linq; + public static void Main() + { + KeywordCharacters(); + } - public class Program + private static void KeywordCharacters() { - public static void Main() - { - KeywordCharacters(); - } + #region INCLUDE + var selection = + from word in CSharp.Keywords + #region HIGHLIGHT + from character in word + #endregion HIGHLIGHT + select character; + #endregion INCLUDE - private static void KeywordCharacters() + foreach (var wordCharacter in selection) { - #region INCLUDE - var selection = - from word in CSharp.Keywords - #region HIGHLIGHT - from character in word - #endregion HIGHLIGHT - select character; - #endregion INCLUDE - - foreach (var wordCharacter in selection) - { - Console.WriteLine(wordCharacter); - } + Console.WriteLine(wordCharacter); } } } diff --git a/src/Chapter16/Listing16.14.CartesianProduct.cs b/src/Chapter16/Listing16.14.CartesianProduct.cs index b062b2bc3..2a0770824 100644 --- a/src/Chapter16/Listing16.14.CartesianProduct.cs +++ b/src/Chapter16/Listing16.14.CartesianProduct.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_14 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_14; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +using System; +using System.Collections.Generic; +using System.Linq; + +public class Program { - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - using System; - using System.Collections.Generic; - using System.Linq; + public static void Main() + { + KeywordProducts(); + } - public class Program + private static void KeywordProducts() { - public static void Main() - { - KeywordProducts(); - } + #region INCLUDE + var numbers = new[] { 1, 2, 3 }; + IEnumerable<(string Word, int Number)> product = + from word in CSharp.Keywords + #region HIGHLIGHT + from number in numbers + #endregion HIGHLIGHT + select (word, number); + #endregion INCLUDE - private static void KeywordProducts() + foreach ((string word, int number) in product) { - #region INCLUDE - var numbers = new[] { 1, 2, 3 }; - IEnumerable<(string Word, int Number)> product = - from word in CSharp.Keywords - #region HIGHLIGHT - from number in numbers - #endregion HIGHLIGHT - select (word, number); - #endregion INCLUDE - - foreach ((string word, int number) in product) - { - Console.WriteLine( - $"({word}, {number})"); - } + Console.WriteLine( + $"({word}, {number})"); } } } diff --git a/src/Chapter16/Listing16.15.ObtainingDistinctMembersFromAQueryExpression.cs b/src/Chapter16/Listing16.15.ObtainingDistinctMembersFromAQueryExpression.cs index bec6e87b0..8d186ffa0 100644 --- a/src/Chapter16/Listing16.15.ObtainingDistinctMembersFromAQueryExpression.cs +++ b/src/Chapter16/Listing16.15.ObtainingDistinctMembersFromAQueryExpression.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_15; + +#region INCLUDE +using System; +using System.Linq; +using System.Collections.Generic; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Linq; - using System.Collections.Generic; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - ListMemberNames(); - } - #endregion EXCLUDE - public static void ListMemberNames() + ListMemberNames(); + } + #endregion EXCLUDE + public static void ListMemberNames() + { + IEnumerable enumerableMethodNames = ( + from method in typeof(Enumerable).GetMembers( + System.Reflection.BindingFlags.Static | + System.Reflection.BindingFlags.Public) + orderby method.Name + select method.Name).Distinct(); + foreach(string method in enumerableMethodNames) { - IEnumerable enumerableMethodNames = ( - from method in typeof(Enumerable).GetMembers( - System.Reflection.BindingFlags.Static | - System.Reflection.BindingFlags.Public) - orderby method.Name - select method.Name).Distinct(); - foreach(string method in enumerableMethodNames) - { - Console.Write($"{ method }, "); - } + Console.Write($"{ method }, "); } - //... - #endregion INCLUDE } + //... + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.16.SimpleQueryExpression.cs b/src/Chapter16/Listing16.16.SimpleQueryExpression.cs index 0341d019e..f2f094249 100644 --- a/src/Chapter16/Listing16.16.SimpleQueryExpression.cs +++ b/src/Chapter16/Listing16.16.SimpleQueryExpression.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_16 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_16; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - ShowContextualKeywords1(); - } - #region INCLUDE - private static void ShowContextualKeywords1() - { - IEnumerable selection = - from word in CSharp.Keywords - where !word.Contains('*') - select word; - #region EXCLUDE + ShowContextualKeywords1(); + } + #region INCLUDE + private static void ShowContextualKeywords1() + { + IEnumerable selection = + from word in CSharp.Keywords + where !word.Contains('*') + select word; + #region EXCLUDE - foreach (var selectionWord in selection) - { - Console.WriteLine(Environment.NewLine + selectionWord); - } - #endregion EXCLUDE + foreach (var selectionWord in selection) + { + Console.WriteLine(Environment.NewLine + selectionWord); } - #endregion INCLUDE + #endregion EXCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter16/Listing16.17.StandardQueryOperatorSyntax.cs b/src/Chapter16/Listing16.17.StandardQueryOperatorSyntax.cs index f2f06df57..c0b5e2d64 100644 --- a/src/Chapter16/Listing16.17.StandardQueryOperatorSyntax.cs +++ b/src/Chapter16/Listing16.17.StandardQueryOperatorSyntax.cs @@ -1,31 +1,30 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_17 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; - using System; - using System.Collections.Generic; - using System.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16_17; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter16.Listing16; +using System; +using System.Collections.Generic; +using System.Linq; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - ShowContextualKeywords2(); - } - #region INCLUDE - private static void ShowContextualKeywords2() + ShowContextualKeywords2(); + } + #region INCLUDE + private static void ShowContextualKeywords2() + { + #region HIGHLIGHT + IEnumerable selection = + CSharp.Keywords.Where(word => !word.Contains('*')); + #endregion HIGHLIGHT + #region EXCLUDE + foreach (var selectionWord in selection) { - #region HIGHLIGHT - IEnumerable selection = - CSharp.Keywords.Where(word => !word.Contains('*')); - #endregion HIGHLIGHT - #region EXCLUDE - foreach (var selectionWord in selection) - { - Console.WriteLine(Environment.NewLine + "{0}", - selectionWord); - } - #endregion EXCLUDE + Console.WriteLine(Environment.NewLine + "{0}", + selectionWord); } - #endregion INCLUDE + #endregion EXCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter17/Listing17.01.UsingList.cs b/src/Chapter17/Listing17.01.UsingList.cs index 4d10232ec..965ea1606 100644 --- a/src/Chapter17/Listing17.01.UsingList.cs +++ b/src/Chapter17/Listing17.01.UsingList.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_01 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_01; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - List list = new List - { "Sneezy", "Happy", "Dopey", "Doc", "Sleepy", "Bashful", "Grumpy"}; + List list = new List + { "Sneezy", "Happy", "Dopey", "Doc", "Sleepy", "Bashful", "Grumpy"}; - list.Sort(); + list.Sort(); - Console.WriteLine( - $"In alphabetical order { list[0] } is the " - + $"first dwarf while { list[^1] } is the last."); + Console.WriteLine( + $"In alphabetical order { list[0] } is the " + + $"first dwarf while { list[^1] } is the last."); - list.Remove("Grumpy"); - } + list.Remove("Grumpy"); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.02.ImplementingIComparer.cs b/src/Chapter17/Listing17.02.ImplementingIComparer.cs index f35cc4823..90b9cb06b 100644 --- a/src/Chapter17/Listing17.02.ImplementingIComparer.cs +++ b/src/Chapter17/Listing17.02.ImplementingIComparer.cs @@ -1,77 +1,76 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_02; + +#region INCLUDE +using System; +using System.Collections.Generic; +#region EXCLUDE +public class Program { - #region INCLUDE - using System; - using System.Collections.Generic; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() + List list = new List { - List list = new List - { - // Lists automatically expand as elements - // are added - new Contact("Sneezy", "Dwarf"), - new Contact("Happy", "Dwarf"), - new Contact("Dopey", "Dwarf"), - new Contact("Doc", "Dwarf"), - new Contact("Sleepy", "Dwarf"), - new Contact("Bashful", "Dwarf"), - new Contact("Grumpy", "Dwarf"), - new Contact("Duplicate", "Dwarf"), - new Contact("Duplicate", "Scarf") - }; + // Lists automatically expand as elements + // are added + new Contact("Sneezy", "Dwarf"), + new Contact("Happy", "Dwarf"), + new Contact("Dopey", "Dwarf"), + new Contact("Doc", "Dwarf"), + new Contact("Sleepy", "Dwarf"), + new Contact("Bashful", "Dwarf"), + new Contact("Grumpy", "Dwarf"), + new Contact("Duplicate", "Dwarf"), + new Contact("Duplicate", "Scarf") + }; - IComparer comparer = new NameComparison(); + IComparer comparer = new NameComparison(); - list.Sort(comparer); + list.Sort(comparer); - foreach(Contact dwarf in list) - { - Console.WriteLine(dwarf.LastName + ", " + dwarf.FirstName); - } + foreach(Contact dwarf in list) + { + Console.WriteLine(dwarf.LastName + ", " + dwarf.FirstName); } } - #endregion EXCLUDE - public class Contact - { - public string FirstName { get; private set; } - public string LastName { get; private set; } +} +#endregion EXCLUDE +public class Contact +{ + public string FirstName { get; private set; } + public string LastName { get; private set; } - public Contact(string firstName, string lastName) - { - this.FirstName = firstName; - this.LastName = lastName; - } + public Contact(string firstName, string lastName) + { + this.FirstName = firstName; + this.LastName = lastName; } - public class NameComparison : IComparer +} +public class NameComparison : IComparer +{ + public int Compare(Contact? x, Contact? y) { - public int Compare(Contact? x, Contact? y) - { - if(Object.ReferenceEquals(x, y)) - return 0; - if(x == null) - return 1; - if(y == null) - return -1; - int result = StringCompare(x.LastName, y.LastName); - if(result == 0) - result = StringCompare(x.FirstName, y.FirstName); - return result; - } + if(Object.ReferenceEquals(x, y)) + return 0; + if(x == null) + return 1; + if(y == null) + return -1; + int result = StringCompare(x.LastName, y.LastName); + if(result == 0) + result = StringCompare(x.FirstName, y.FirstName); + return result; + } - private static int StringCompare(string? x, string? y) - { - if(Object.ReferenceEquals(x, y)) - return 0; - if(x == null) - return 1; - if(y == null) - return -1; - return x.CompareTo(y); - } + private static int StringCompare(string? x, string? y) + { + if(Object.ReferenceEquals(x, y)) + return 0; + if(x == null) + return 1; + if(y == null) + return -1; + return x.CompareTo(y); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.03.UsingTheBitComplementOfTheBinarySearchResult.cs b/src/Chapter17/Listing17.03.UsingTheBitComplementOfTheBinarySearchResult.cs index 9d839edf0..576f3c14a 100644 --- a/src/Chapter17/Listing17.03.UsingTheBitComplementOfTheBinarySearchResult.cs +++ b/src/Chapter17/Listing17.03.UsingTheBitComplementOfTheBinarySearchResult.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_03 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_03; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - List list = new List(); - int search; + List list = new List(); + int search; - list.Add("public"); - list.Add("protected"); - list.Add("private"); + list.Add("public"); + list.Add("protected"); + list.Add("private"); - list.Sort(); + list.Sort(); - search = list.BinarySearch("protected internal"); - if(search < 0) - { - list.Insert(~search, "protected internal"); - } + search = list.BinarySearch("protected internal"); + if(search < 0) + { + list.Insert(~search, "protected internal"); + } - foreach(string accessModifier in list) - { - Console.WriteLine(accessModifier); - } + foreach(string accessModifier in list) + { + Console.WriteLine(accessModifier); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.04.DemonstratingFindAllAndItsPredicateParameter.cs b/src/Chapter17/Listing17.04.DemonstratingFindAllAndItsPredicateParameter.cs index f6b742b1a..41d7ac578 100644 --- a/src/Chapter17/Listing17.04.DemonstratingFindAllAndItsPredicateParameter.cs +++ b/src/Chapter17/Listing17.04.DemonstratingFindAllAndItsPredicateParameter.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_04 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_04; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - List list = new List(); - list.Add(1); - list.Add(2); - list.Add(3); - list.Add(2); + List list = new List(); + list.Add(1); + list.Add(2); + list.Add(3); + list.Add(2); - #region HIGHLIGHT - List results = list.FindAll(Even); - #endregion HIGHLIGHT + #region HIGHLIGHT + List results = list.FindAll(Even); + #endregion HIGHLIGHT - #region HIGHLIGHT - foreach (int number in results) - #endregion HIGHLIGHT - { - Console.WriteLine(number); - } + #region HIGHLIGHT + foreach (int number in results) + #endregion HIGHLIGHT + { + Console.WriteLine(number); } - public static bool Even(int value) => - (value % 2) == 0; } - #endregion INCLUDE + public static bool Even(int value) => + (value % 2) == 0; } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.05.AddingItemsToADictionary.cs b/src/Chapter17/Listing17.05.AddingItemsToADictionary.cs index f12e726df..fc5b664f7 100644 --- a/src/Chapter17/Listing17.05.AddingItemsToADictionary.cs +++ b/src/Chapter17/Listing17.05.AddingItemsToADictionary.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_05 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_05; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + var colorMap = new Dictionary { - var colorMap = new Dictionary - { - ["Error"] = ConsoleColor.Red, - ["Warning"] = ConsoleColor.Yellow, - ["Information"] = ConsoleColor.Green - }; - #region HIGHLIGHT - colorMap.Add("Verbose", ConsoleColor.White); - #endregion HIGHLIGHT - #region EXCLUDE + ["Error"] = ConsoleColor.Red, + ["Warning"] = ConsoleColor.Yellow, + ["Information"] = ConsoleColor.Green + }; + #region HIGHLIGHT + colorMap.Add("Verbose", ConsoleColor.White); + #endregion HIGHLIGHT + #region EXCLUDE - Print(colorMap); - } + Print(colorMap); + } - private static void Print(IEnumerable> items) + private static void Print(IEnumerable> items) + { + foreach (KeyValuePair item in items) { - foreach (KeyValuePair item in items) - { - Console.ForegroundColor = item.Value; - Console.WriteLine(item.Key); - } - #endregion EXCLUDE + Console.ForegroundColor = item.Value; + Console.WriteLine(item.Key); } + #endregion EXCLUDE } -#endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.06.InsertingItemsInADictionaryUsingTheIndexOperator.cs b/src/Chapter17/Listing17.06.InsertingItemsInADictionaryUsingTheIndexOperator.cs index bca58a764..42bddef5b 100644 --- a/src/Chapter17/Listing17.06.InsertingItemsInADictionaryUsingTheIndexOperator.cs +++ b/src/Chapter17/Listing17.06.InsertingItemsInADictionaryUsingTheIndexOperator.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_06 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_06; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - var colorMap = new Dictionary - { - ["Error"] = ConsoleColor.Red, - ["Warning"] = ConsoleColor.Yellow, - ["Information"] = ConsoleColor.Green - }; + var colorMap = new Dictionary + { + ["Error"] = ConsoleColor.Red, + ["Warning"] = ConsoleColor.Yellow, + ["Information"] = ConsoleColor.Green + }; - #region HIGHLIGHT - colorMap["Verbose"] = ConsoleColor.White; - colorMap["Error"] = ConsoleColor.Cyan; - #endregion HIGHLIGHT + #region HIGHLIGHT + colorMap["Verbose"] = ConsoleColor.White; + colorMap["Error"] = ConsoleColor.Cyan; + #endregion HIGHLIGHT - #region EXCLUDE - Print(colorMap); - } + #region EXCLUDE + Print(colorMap); + } - private static void Print(IEnumerable> items) + private static void Print(IEnumerable> items) + { + foreach (KeyValuePair item in items) { - foreach (KeyValuePair item in items) - { - Console.ForegroundColor = item.Value; - Console.WriteLine(item.Key); - } - #endregion EXCLUDE + Console.ForegroundColor = item.Value; + Console.WriteLine(item.Key); } + #endregion EXCLUDE } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.07.IteratingOverDictionaryWithForeach.cs b/src/Chapter17/Listing17.07.IteratingOverDictionaryWithForeach.cs index 8d936f046..16f5314ad 100644 --- a/src/Chapter17/Listing17.07.IteratingOverDictionaryWithForeach.cs +++ b/src/Chapter17/Listing17.07.IteratingOverDictionaryWithForeach.cs @@ -1,37 +1,36 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_07 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_07; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - var colorMap = new Dictionary - { - ["Error"] = ConsoleColor.Red, - ["Warning"] = ConsoleColor.Yellow, - ["Information"] = ConsoleColor.Green, - ["Verbose"] = ConsoleColor.White - }; + var colorMap = new Dictionary + { + ["Error"] = ConsoleColor.Red, + ["Warning"] = ConsoleColor.Yellow, + ["Information"] = ConsoleColor.Green, + ["Verbose"] = ConsoleColor.White + }; - Print(colorMap); - } + Print(colorMap); + } + #region HIGHLIGHT + private static void Print( + IEnumerable> items) + #endregion HIGHLIGHT + { #region HIGHLIGHT - private static void Print( - IEnumerable> items) + foreach (KeyValuePair item in items) #endregion HIGHLIGHT { - #region HIGHLIGHT - foreach (KeyValuePair item in items) - #endregion HIGHLIGHT - { - Console.ForegroundColor = item.Value; - Console.WriteLine(item.Key); - } - } + Console.ForegroundColor = item.Value; + Console.WriteLine(item.Key); + } } +} #endregion INCLUDE -} \ No newline at end of file diff --git a/src/Chapter17/Listing17.07a.IteratingOverSortedDictionaryWithForeach.Placeholder.cs b/src/Chapter17/Listing17.07a.IteratingOverSortedDictionaryWithForeach.Placeholder.cs index 73f9c8651..0c4b73984 100644 --- a/src/Chapter17/Listing17.07a.IteratingOverSortedDictionaryWithForeach.Placeholder.cs +++ b/src/Chapter17/Listing17.07a.IteratingOverSortedDictionaryWithForeach.Placeholder.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_07a -{ - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_07a; + +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { #if !PRECSHARP5 - var colorMap = new SortedDictionary - { - ["Error"] = ConsoleColor.Red, - ["Warning"] = ConsoleColor.Yellow, - ["Information"] = ConsoleColor.Green, - ["Verbose"] = ConsoleColor.White - }; + var colorMap = new SortedDictionary + { + ["Error"] = ConsoleColor.Red, + ["Warning"] = ConsoleColor.Yellow, + ["Information"] = ConsoleColor.Green, + ["Verbose"] = ConsoleColor.White + }; #else - Dictionary colorMap = - new Dictionary - { - {"Error", ConsoleColor.Red }, - {"Warning", ConsoleColor.Yellow }, - {"Information", ConsoleColor.Green }, - {"Verbose", ConsoleColor.White} - }; + Dictionary colorMap = + new Dictionary + { + {"Error", ConsoleColor.Red }, + {"Warning", ConsoleColor.Yellow }, + {"Information", ConsoleColor.Green }, + {"Verbose", ConsoleColor.White} + }; #endif - Print(colorMap); - } + Print(colorMap); + } - private static void Print( - IEnumerable> items) + private static void Print( + IEnumerable> items) + { + foreach (KeyValuePair item in items) { - foreach (KeyValuePair item in items) - { - Console.ForegroundColor = item.Value; - Console.WriteLine(item.Key); - } - } + Console.ForegroundColor = item.Value; + Console.WriteLine(item.Key); + } } } \ No newline at end of file diff --git a/src/Chapter17/Listing17.08.ImplementingIEqualityComparer.cs b/src/Chapter17/Listing17.08.ImplementingIEqualityComparer.cs index 6c0d53bb0..fc4c95a79 100644 --- a/src/Chapter17/Listing17.08.ImplementingIEqualityComparer.cs +++ b/src/Chapter17/Listing17.08.ImplementingIEqualityComparer.cs @@ -1,41 +1,40 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_08 -{ - #region INCLUDE - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_08; + +#region INCLUDE +using System.Collections.Generic; - public class ContactEquality : IEqualityComparer +public class ContactEquality : IEqualityComparer +{ + public bool Equals(Contact? x, Contact? y) { - public bool Equals(Contact? x, Contact? y) - { - if(object.ReferenceEquals(x, y)) - return true; - if(x == null || y == null) - return false; - return x.LastName == y.LastName && - x.FirstName == y.FirstName; - } + if(object.ReferenceEquals(x, y)) + return true; + if(x == null || y == null) + return false; + return x.LastName == y.LastName && + x.FirstName == y.FirstName; + } - public int GetHashCode(Contact x) - { - if(x is null) - return 0; + public int GetHashCode(Contact x) + { + if(x is null) + return 0; - int h1 = x.FirstName == null ? 0 : x.FirstName.GetHashCode(); - int h2 = x.LastName == null ? 0 : x.LastName.GetHashCode(); - return h1 * 23 + h2; - } + int h1 = x.FirstName == null ? 0 : x.FirstName.GetHashCode(); + int h2 = x.LastName == null ? 0 : x.LastName.GetHashCode(); + return h1 * 23 + h2; } - #endregion INCLUDE +} +#endregion INCLUDE - public class Contact - { - public string FirstName { get; private set; } - public string LastName { get; private set; } +public class Contact +{ + public string FirstName { get; private set; } + public string LastName { get; private set; } - public Contact(string firstName, string lastName) - { - this.FirstName = firstName; - this.LastName = lastName; - } + public Contact(string firstName, string lastName) + { + this.FirstName = firstName; + this.LastName = lastName; } } \ No newline at end of file diff --git a/src/Chapter17/Listing17.09.DefiningAnIndexer.cs b/src/Chapter17/Listing17.09.DefiningAnIndexer.cs index 02479abf6..2aa770956 100644 --- a/src/Chapter17/Listing17.09.DefiningAnIndexer.cs +++ b/src/Chapter17/Listing17.09.DefiningAnIndexer.cs @@ -1,81 +1,80 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_09; + +using System; + +// ---- +#region INCLUDE +interface IPair { - using System; + T First { get; } + T Second { get; } + #region HIGHLIGHT + T this[PairItem index] { get; } + #endregion HIGHLIGHT +} - // ---- - #region INCLUDE - interface IPair - { - T First { get; } - T Second { get; } - #region HIGHLIGHT - T this[PairItem index] { get; } - #endregion HIGHLIGHT - } +public enum PairItem +{ + First, + Second +} - public enum PairItem +public struct Pair : IPair +{ + public Pair(T first, T second) { - First, - Second + First = first; + Second = second; } - public struct Pair : IPair - { - public Pair(T first, T second) - { - First = first; - Second = second; - } + public T First { get; } + public T Second { get; } - public T First { get; } - public T Second { get; } - - #region HIGHLIGHT - public T this[PairItem index] + #region HIGHLIGHT + public T this[PairItem index] + { + get { - get + #endregion HIGHLIGHT + switch (index) { - #endregion HIGHLIGHT - switch (index) - { - case PairItem.First: - return First; - case PairItem.Second: - return Second; - default: - throw new NotImplementedException( - $"The enum { index.ToString() } has not been implemented"); + case PairItem.First: + return First; + case PairItem.Second: + return Second; + default: + throw new NotImplementedException( + $"The enum { index.ToString() } has not been implemented"); - } } - #region EXCLUDE + } + #region EXCLUDE - /* - // In keeping with the principal that structs should - // be read-only, the setter is commented out + /* + // In keeping with the principal that structs should + // be read-only, the setter is commented out - set + set + { + switch(index) { - switch(index) - { - case PairItem.First: - First = value; - break; - case PairItem.Second: - Second = value; - break; - default: - throw new NotImplementedException( - string.Format( - "The enum {0} has not been implemented", - index.ToString())); - } + case PairItem.First: + First = value; + break; + case PairItem.Second: + Second = value; + break; + default: + throw new NotImplementedException( + string.Format( + "The enum {0} has not been implemented", + index.ToString())); } - */ - #endregion EXCLUDE - #region HIGHLIGHT } - #endregion HIGHLIGHT + */ + #endregion EXCLUDE + #region HIGHLIGHT } - #endregion INCLUDE + #endregion HIGHLIGHT } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.10.ChangingTheIndexersDefaultName.cs b/src/Chapter17/Listing17.10.ChangingTheIndexersDefaultName.cs index 7d758712d..90b9b50f7 100644 --- a/src/Chapter17/Listing17.10.ChangingTheIndexersDefaultName.cs +++ b/src/Chapter17/Listing17.10.ChangingTheIndexersDefaultName.cs @@ -1,56 +1,55 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_10; + +using System; + +// ---- + +interface IPair { - using System; + T First { get; } - // ---- + T Second { get; } - interface IPair - { - T First { get; } + T this[PairItem index] { get; } +} - T Second { get; } +// ---- - T this[PairItem index] { get; } - } +public enum PairItem +{ + First, + Second +} - // ---- +// ---- - public enum PairItem +public struct Pair : IPair +{ + public Pair(T first, T second) { - First, - Second + First = first; + Second = second; } - // ---- + public T First { get; } // C# 6.0 Getter-Only Autoproperty - public struct Pair : IPair + public T Second { get; } // C# 6.0 Getter-Only Autoproperty + #region INCLUDE + [System.Runtime.CompilerServices.IndexerName("Entry")] + public T this[PairItem index] { - public Pair(T first, T second) - { - First = first; - Second = second; - } - - public T First { get; } // C# 6.0 Getter-Only Autoproperty - - public T Second { get; } // C# 6.0 Getter-Only Autoproperty - #region INCLUDE - [System.Runtime.CompilerServices.IndexerName("Entry")] - public T this[PairItem index] + #region EXCLUDE + get { - #region EXCLUDE - get + return index switch { - return index switch - { - PairItem.First => First, - PairItem.Second => Second, - _ => throw new NotImplementedException( - $"The enum {index} has not been implemented"), - }; - } - #endregion EXCLUDE + PairItem.First => First, + PairItem.Second => Second, + _ => throw new NotImplementedException( + $"The enum {index} has not been implemented"), + }; } - #endregion INCLUDE + #endregion EXCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter17/Listing17.11.DefiningAnIndexOperatorWithVariableParameters.cs b/src/Chapter17/Listing17.11.DefiningAnIndexOperatorWithVariableParameters.cs index 4b6a84152..89487ea82 100644 --- a/src/Chapter17/Listing17.11.DefiningAnIndexOperatorWithVariableParameters.cs +++ b/src/Chapter17/Listing17.11.DefiningAnIndexOperatorWithVariableParameters.cs @@ -1,91 +1,90 @@ using AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_10; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_11; + +#region INCLUDE +using System; + +public class BinaryTree { - #region INCLUDE - using System; + #region EXCLUDE + public BinaryTree(T value) + { + Value = value; + } - public class BinaryTree + /// + /// Returns the BinaryTree at a particular location + /// + /// An array of PairItems + /// pointing to a particular branch. + /// + /// familyTree.SubItems.Second.SubItems[PairItem.First].Value + /// + #endregion EXCLUDE + public BinaryTree this[params PairItem[]? branches] { - #region EXCLUDE - public BinaryTree(T value) + get { - Value = value; - } + BinaryTree currentNode = this; - /// - /// Returns the BinaryTree at a particular location - /// - /// An array of PairItems - /// pointing to a particular branch. - /// - /// familyTree.SubItems.Second.SubItems[PairItem.First].Value - /// - #endregion EXCLUDE - public BinaryTree this[params PairItem[]? branches] - { - get - { - BinaryTree currentNode = this; + // Allow either an empty array or null + // to refer to the root node + int totalLevels = branches?.Length ?? 0; + int currentLevel = 0; - // Allow either an empty array or null - // to refer to the root node - int totalLevels = branches?.Length ?? 0; - int currentLevel = 0; + while (currentLevel < totalLevels) + { + System.Diagnostics.Debug.Assert(branches != null, + $"{ nameof(branches) } != null"); - while (currentLevel < totalLevels) + currentNode = currentNode.SubItems[ + branches[currentLevel]]; + if (currentNode == null) { - System.Diagnostics.Debug.Assert(branches != null, - $"{ nameof(branches) } != null"); - - currentNode = currentNode.SubItems[ - branches[currentLevel]]; - if (currentNode == null) - { - // The binary tree at this location is null - throw new IndexOutOfRangeException(); - } - currentLevel++; + // The binary tree at this location is null + throw new IndexOutOfRangeException(); } - return currentNode; + currentLevel++; } + return currentNode; } - #region EXCLUDE + } + #region EXCLUDE - public T Value { get; set; } + public T Value { get; set; } - public Pair> SubItems {get;set;} - #endregion EXCLUDE - } - #endregion INCLUDE + public Pair> SubItems {get;set;} + #endregion EXCLUDE +} +#endregion INCLUDE - public class Program +public class Program +{ + public static void Main() { - public static void Main() + // JFK + var jfkFamilyTree = new BinaryTree( + "John Fitzgerald Kennedy") { - // JFK - var jfkFamilyTree = new BinaryTree( - "John Fitzgerald Kennedy") - { - SubItems = new Pair>( - new BinaryTree("Joseph Patrick Kennedy") - { - // Grandparents (Father's side) - SubItems = new Pair>( - new BinaryTree("Patrick Joseph Kennedy"), - new BinaryTree("Mary Augusta Hickey")) - }, - new BinaryTree("Rose Elizabeth Fitzgerald") - { - // Grandparents (Mother's side) - SubItems = new Pair>( - new BinaryTree("John Francis Fitzgerald"), - new BinaryTree("Mary Josephine Hannon")) - }) - }; + SubItems = new Pair>( + new BinaryTree("Joseph Patrick Kennedy") + { + // Grandparents (Father's side) + SubItems = new Pair>( + new BinaryTree("Patrick Joseph Kennedy"), + new BinaryTree("Mary Augusta Hickey")) + }, + new BinaryTree("Rose Elizabeth Fitzgerald") + { + // Grandparents (Mother's side) + SubItems = new Pair>( + new BinaryTree("John Francis Fitzgerald"), + new BinaryTree("Mary Josephine Hannon")) + }) + }; - Console.WriteLine(jfkFamilyTree[PairItem.Second, PairItem.First].Value); - Console.WriteLine(jfkFamilyTree[PairItem.Second, PairItem.Second].Value); - } + Console.WriteLine(jfkFamilyTree[PairItem.Second, PairItem.First].Value); + Console.WriteLine(jfkFamilyTree[PairItem.Second, PairItem.Second].Value); } } diff --git a/src/Chapter17/Listing17.12.IteratorInterfacesPattern.cs b/src/Chapter17/Listing17.12.IteratorInterfacesPattern.cs index 5a2844123..0acef63a8 100644 --- a/src/Chapter17/Listing17.12.IteratorInterfacesPattern.cs +++ b/src/Chapter17/Listing17.12.IteratorInterfacesPattern.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_12; + +#region INCLUDE +using System.Collections; +using System.Collections.Generic; + +public class BinaryTree : +#region HIGHLIGHT +IEnumerable +#endregion HIGHLIGHT { - #region INCLUDE - using System.Collections; - using System.Collections.Generic; + public BinaryTree(T value) + { + Value = value; + } - public class BinaryTree : + #region IEnumerable #region HIGHLIGHT - IEnumerable + public IEnumerator GetEnumerator() #endregion HIGHLIGHT { - public BinaryTree(T value) - { - Value = value; - } - - #region IEnumerable - #region HIGHLIGHT - public IEnumerator GetEnumerator() - #endregion HIGHLIGHT - { - #region EXCLUDE - return new List.Enumerator(); // This will be implemented in 16.16 - } - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); // This will be implemented in 16.16 - #endregion EXCLUDE - } - #endregion IEnumerable - - public T Value { get; } - public Pair> SubItems { get; set; } + #region EXCLUDE + return new List.Enumerator(); // This will be implemented in 16.16 } + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); // This will be implemented in 16.16 + #endregion EXCLUDE + } + #endregion IEnumerable - public struct Pair + public T Value { get; } + public Pair> SubItems { get; set; } +} + +public struct Pair +{ + public Pair(T first, T second) : this() { - public Pair(T first, T second) : this() - { - First = first; - Second = second; - } - public T First { get; } - public T Second { get; } + First = first; + Second = second; } - #endregion INCLUDE + public T First { get; } + public T Second { get; } } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.13.YieldingTheCSharpKeywordsSequentially.cs b/src/Chapter17/Listing17.13.YieldingTheCSharpKeywordsSequentially.cs index de1bb18ab..0bd528249 100644 --- a/src/Chapter17/Listing17.13.YieldingTheCSharpKeywordsSequentially.cs +++ b/src/Chapter17/Listing17.13.YieldingTheCSharpKeywordsSequentially.cs @@ -1,50 +1,49 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_13 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_13; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class CSharpBuiltInTypes : IEnumerable +public class CSharpBuiltInTypes : IEnumerable +{ + public IEnumerator GetEnumerator() { - public IEnumerator GetEnumerator() - { - yield return "object"; - yield return "byte"; - yield return "uint"; - yield return "ulong"; - yield return "float"; - yield return "char"; - yield return "bool"; - yield return "ushort"; - yield return "decimal"; - yield return "int"; - yield return "sbyte"; - yield return "short"; - yield return "long"; - yield return "void"; - yield return "double"; - yield return "string"; - } + yield return "object"; + yield return "byte"; + yield return "uint"; + yield return "ulong"; + yield return "float"; + yield return "char"; + yield return "bool"; + yield return "ushort"; + yield return "decimal"; + yield return "int"; + yield return "sbyte"; + yield return "short"; + yield return "long"; + yield return "void"; + yield return "double"; + yield return "string"; + } - // The IEnumerable.GetEnumerator method is also required - // because IEnumerable derives from IEnumerable - System.Collections.IEnumerator - System.Collections.IEnumerable.GetEnumerator() - { - // Invoke IEnumerator GetEnumerator() above - return GetEnumerator(); - } + // The IEnumerable.GetEnumerator method is also required + // because IEnumerable derives from IEnumerable + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() + { + // Invoke IEnumerator GetEnumerator() above + return GetEnumerator(); } - public class Program +} +public class Program +{ + public static void Main() { - public static void Main() + var keywords = new CSharpBuiltInTypes(); + foreach (string keyword in keywords) { - var keywords = new CSharpBuiltInTypes(); - foreach (string keyword in keywords) - { - Console.WriteLine(keyword); - } + Console.WriteLine(keyword); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.14.UsingYieldToImplementBinaryTree.cs b/src/Chapter17/Listing17.14.UsingYieldToImplementBinaryTree.cs index 8e341bf74..e3201c08c 100644 --- a/src/Chapter17/Listing17.14.UsingYieldToImplementBinaryTree.cs +++ b/src/Chapter17/Listing17.14.UsingYieldToImplementBinaryTree.cs @@ -1,61 +1,60 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_14 -{ - using System; - using Listing17_10; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_14; - using System.Collections.Generic; - #region INCLUDE - public struct Pair : IPair, - #region HIGHLIGHT - IEnumerable - #endregion HIGHLIGHT +using System; +using Listing17_10; + +using System.Collections.Generic; +#region INCLUDE +public struct Pair : IPair, +#region HIGHLIGHT +IEnumerable +#endregion HIGHLIGHT +{ + public Pair(T first, T second) : this() { - public Pair(T first, T second) : this() - { - First = first; - Second = second; - } - public T First { get; } - public T Second { get; } - #region EXCLUDE - #region Indexer - public T this[PairItem index] + First = first; + Second = second; + } + public T First { get; } + public T Second { get; } + #region EXCLUDE + #region Indexer + public T this[PairItem index] + { + get { - get + switch(index) { - switch(index) - { - case PairItem.First: - return First; - case PairItem.Second: - return Second; - default: - throw new NotImplementedException( - string.Format( - "The enum {0} has not been implemented", - index.ToString())); - } + case PairItem.First: + return First; + case PairItem.Second: + return Second; + default: + throw new NotImplementedException( + string.Format( + "The enum {0} has not been implemented", + index.ToString())); } - #endregion Indexer } - #endregion EXCLUDE - #region HIGHLIGHT - #region IEnumerable - public IEnumerator GetEnumerator() - { - yield return First; - yield return Second; - } - #endregion IEnumerable + #endregion Indexer + } + #endregion EXCLUDE + #region HIGHLIGHT + #region IEnumerable + public IEnumerator GetEnumerator() + { + yield return First; + yield return Second; + } + #endregion IEnumerable - #region IEnumerable Members - System.Collections.IEnumerator - System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - #endregion IEnumerable Members - #endregion HIGHLIGHT + #region IEnumerable Members + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); } + #endregion IEnumerable Members + #endregion HIGHLIGHT +} #endregion INCLUDE -} \ No newline at end of file diff --git a/src/Chapter17/Listing17.15.UsingPair.GetEnumeratorViaForeach.cs b/src/Chapter17/Listing17.15.UsingPair.GetEnumeratorViaForeach.cs index dc2e39d63..375d09739 100644 --- a/src/Chapter17/Listing17.15.UsingPair.GetEnumeratorViaForeach.cs +++ b/src/Chapter17/Listing17.15.UsingPair.GetEnumeratorViaForeach.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_15 -{ - using System; - using Listing17_14; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_15; + +using System; +using Listing17_14; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region INCLUDE + var fullname = new Pair("Inigo", "Montoya"); + foreach(string name in fullname) { - #region INCLUDE - var fullname = new Pair("Inigo", "Montoya"); - foreach(string name in fullname) - { - Console.WriteLine(name); - } - #endregion INCLUDE + Console.WriteLine(name); } + #endregion INCLUDE } } diff --git a/src/Chapter17/Listing17.16.PlacingYieldReturnStatementsWithinALoop.cs b/src/Chapter17/Listing17.16.PlacingYieldReturnStatementsWithinALoop.cs index c094d0ed3..07c7047a5 100644 --- a/src/Chapter17/Listing17.16.PlacingYieldReturnStatementsWithinALoop.cs +++ b/src/Chapter17/Listing17.16.PlacingYieldReturnStatementsWithinALoop.cs @@ -1,54 +1,53 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_16 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_16; + +using System.Collections.Generic; +using Listing17_14; +#region INCLUDE +public class BinaryTree : + IEnumerable { - using System.Collections.Generic; - using Listing17_14; - #region INCLUDE - public class BinaryTree : - IEnumerable + #region EXCLUDE + public BinaryTree(T value) { - #region EXCLUDE - public BinaryTree(T value) - { - Value = value; - } - #endregion EXCLUDE - #region IEnumerable - public IEnumerator GetEnumerator() - { - // Return the item at this node - yield return Value; + Value = value; + } + #endregion EXCLUDE + #region IEnumerable + public IEnumerator GetEnumerator() + { + // Return the item at this node + yield return Value; - // Iterate through each of the elements in the pair - #region HIGHLIGHT - foreach (BinaryTree? tree in SubItems) + // Iterate through each of the elements in the pair + #region HIGHLIGHT + foreach (BinaryTree? tree in SubItems) + { + if(tree != null) { - if(tree != null) + // Since each element in the pair is a tree, + // traverse the tree and yield each + // element + foreach(T item in tree) { - // Since each element in the pair is a tree, - // traverse the tree and yield each - // element - foreach(T item in tree) - { - yield return item; - } + yield return item; } } - #endregion HIGHLIGHT } - #endregion IEnumerable - - #region IEnumerable Members - System.Collections.IEnumerator - System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - #endregion - #region EXCLUDE - public T Value { get; } // C# 6.0 Getter-only Autoproperty + #endregion HIGHLIGHT + } + #endregion IEnumerable - public Pair> SubItems { get; set; } - #endregion EXCLUDE + #region IEnumerable Members + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); } - #endregion INCLUDE + #endregion + #region EXCLUDE + public T Value { get; } // C# 6.0 Getter-only Autoproperty + + public Pair> SubItems { get; set; } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter17/Listing17.17.UsingForeachWithBinaryTree.cs b/src/Chapter17/Listing17.17.UsingForeachWithBinaryTree.cs index 63211236e..ec7a6a345 100644 --- a/src/Chapter17/Listing17.17.UsingForeachWithBinaryTree.cs +++ b/src/Chapter17/Listing17.17.UsingForeachWithBinaryTree.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_17 -{ - using System; - using Listing17_14; - using Listing17_16; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_17; + +using System; +using Listing17_14; +using Listing17_16; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region INCLUDE + // JFK + var jfkFamilyTree = new BinaryTree( + "John Fitzgerald Kennedy") { - #region INCLUDE - // JFK - var jfkFamilyTree = new BinaryTree( - "John Fitzgerald Kennedy") - { - SubItems = new Pair>( - new BinaryTree("Joseph Patrick Kennedy") - { - // Grandparents (Father's side) - SubItems = new Pair>( - new BinaryTree("Patrick Joseph Kennedy"), - new BinaryTree("Mary Augusta Hickey")) - }, - new BinaryTree("Rose Elizabeth Fitzgerald") - { - // Grandparents (Mother's side) - SubItems = new Pair>( - new BinaryTree("John Francis Fitzgerald"), - new BinaryTree("Mary Josephine Hannon")) - }) - }; + SubItems = new Pair>( + new BinaryTree("Joseph Patrick Kennedy") + { + // Grandparents (Father's side) + SubItems = new Pair>( + new BinaryTree("Patrick Joseph Kennedy"), + new BinaryTree("Mary Augusta Hickey")) + }, + new BinaryTree("Rose Elizabeth Fitzgerald") + { + // Grandparents (Mother's side) + SubItems = new Pair>( + new BinaryTree("John Francis Fitzgerald"), + new BinaryTree("Mary Josephine Hannon")) + }) + }; - #region HIGHLIGHT - foreach (string name in jfkFamilyTree) - { - Console.WriteLine(name); - } - #endregion HIGHLIGHT - #endregion INCLUDE + #region HIGHLIGHT + foreach (string name in jfkFamilyTree) + { + Console.WriteLine(name); } + #endregion HIGHLIGHT + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter17/Listing17.18.EscapingIterationViaYieldBreak.cs b/src/Chapter17/Listing17.18.EscapingIterationViaYieldBreak.cs index 30d9fde74..2f6aab0c0 100644 --- a/src/Chapter17/Listing17.18.EscapingIterationViaYieldBreak.cs +++ b/src/Chapter17/Listing17.18.EscapingIterationViaYieldBreak.cs @@ -1,72 +1,71 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_18 -{ - using System; - using Listing17_10; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_18; + +using System; +using Listing17_10; +using System.Collections.Generic; - public struct Pair : IPair, IEnumerable +public struct Pair : IPair, IEnumerable +{ + #region Members + public Pair(T first, T second) { - #region Members - public Pair(T first, T second) - { - First = first; - Second = second; - } - public T First { get; } - public T Second { get; } + First = first; + Second = second; + } + public T First { get; } + public T Second { get; } - public T this[PairItem index] + public T this[PairItem index] + { + get { - get + switch(index) { - switch(index) - { - case PairItem.First: - return First; - case PairItem.Second: - return Second; - default: - throw new NotImplementedException( - string.Format( - "The enum {0} has not been implemented", - index.ToString())); - } + case PairItem.First: + return First; + case PairItem.Second: + return Second; + default: + throw new NotImplementedException( + string.Format( + "The enum {0} has not been implemented", + index.ToString())); } } - #endregion Members + } + #endregion Members - //Listing 17.18 Escaping Iteration via yield break - #region INCLUDE - public System.Collections.Generic.IEnumerable GetNotNullEnumerator() + //Listing 17.18 Escaping Iteration via yield break + #region INCLUDE + public System.Collections.Generic.IEnumerable GetNotNullEnumerator() + { + #region HIGHLIGHT + if ((First == null) || (Second == null)) { - #region HIGHLIGHT - if ((First == null) || (Second == null)) - { - yield break; - } - #endregion HIGHLIGHT - yield return Second; - yield return First; + yield break; } - #endregion INCLUDE + #endregion HIGHLIGHT + yield return Second; + yield return First; + } + #endregion INCLUDE - //Listing 17.18 Escaping Iteration via yield break + //Listing 17.18 Escaping Iteration via yield break - #region IEnumerable - public IEnumerator GetEnumerator() - { - yield return First; - yield return Second; - } - #endregion IEnumerable + #region IEnumerable + public IEnumerator GetEnumerator() + { + yield return First; + yield return Second; + } + #endregion IEnumerable - #region IEnumerable Members - System.Collections.IEnumerator - System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - #endregion + #region IEnumerable Members + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); } + #endregion } diff --git a/src/Chapter17/Listing17.20.UsingYieldReturnInAMethodThatReturnsIEnumberable.cs b/src/Chapter17/Listing17.20.UsingYieldReturnInAMethodThatReturnsIEnumberable.cs index 241a452c3..a8bbe3a3d 100644 --- a/src/Chapter17/Listing17.20.UsingYieldReturnInAMethodThatReturnsIEnumberable.cs +++ b/src/Chapter17/Listing17.20.UsingYieldReturnInAMethodThatReturnsIEnumberable.cs @@ -1,81 +1,80 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_20 -{ - using System; - using Listing17_10; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter17.Listing17_20; + +using System; +using Listing17_10; +using System.Collections.Generic; - #region INCLUDE - public struct Pair : IPair, IEnumerable +#region INCLUDE +public struct Pair : IPair, IEnumerable +{ + #region EXCLUDE + #region Members + public Pair(T first, T second) { - #region EXCLUDE - #region Members - public Pair(T first, T second) - { - First = first; - Second = second; - } - public T First { get; } - public T Second { get; } + First = first; + Second = second; + } + public T First { get; } + public T Second { get; } - public T this[PairItem index] + public T this[PairItem index] + { + get { - get + switch(index) { - switch(index) - { - case PairItem.First: - return First; - case PairItem.Second: - return Second; - default: - throw new NotImplementedException( - string.Format( - "The enum {0} has not been implemented", - index.ToString())); - } + case PairItem.First: + return First; + case PairItem.Second: + return Second; + default: + throw new NotImplementedException( + string.Format( + "The enum {0} has not been implemented", + index.ToString())); } } - #endregion Members + } + #endregion Members - //Listing 16.20 Using yield return in a Method That Returns IEnumerable - #endregion EXCLUDE - #region HIGHLIGHT - public IEnumerable GetReverseEnumerator() - #endregion HIGHLIGHT - { - yield return Second; - yield return First; - } - #region EXCLUDE - #region IEnumerable - public IEnumerator GetEnumerator() - { - yield return First; - yield return Second; - } - #endregion IEnumerable + //Listing 16.20 Using yield return in a Method That Returns IEnumerable + #endregion EXCLUDE + #region HIGHLIGHT + public IEnumerable GetReverseEnumerator() + #endregion HIGHLIGHT + { + yield return Second; + yield return First; + } + #region EXCLUDE + #region IEnumerable + public IEnumerator GetEnumerator() + { + yield return First; + yield return Second; + } + #endregion IEnumerable - #region IEnumerable Members - System.Collections.IEnumerator - System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - #endregion + #region IEnumerable Members + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); } - public class Program + #endregion +} +public class Program +{ + #endregion EXCLUDE + public static void Main() { - #endregion EXCLUDE - public static void Main() + var game = new Pair("Redskins", "Eagles"); + #region HIGHLIGHT + foreach (string name in game.GetReverseEnumerator()) + #endregion HIGHLIGHT { - var game = new Pair("Redskins", "Eagles"); - #region HIGHLIGHT - foreach (string name in game.GetReverseEnumerator()) - #endregion HIGHLIGHT - { - Console.WriteLine(name); - } + Console.WriteLine(name); } - #endregion INCLUDE } + #endregion INCLUDE } diff --git a/src/Chapter18/Listing18.01.UsingTypeGetPropertiesToObtainAnObjectsPublicProperties.cs b/src/Chapter18/Listing18.01.UsingTypeGetPropertiesToObtainAnObjectsPublicProperties.cs index edd9015fd..95abf32af 100644 --- a/src/Chapter18/Listing18.01.UsingTypeGetPropertiesToObtainAnObjectsPublicProperties.cs +++ b/src/Chapter18/Listing18.01.UsingTypeGetPropertiesToObtainAnObjectsPublicProperties.cs @@ -1,20 +1,19 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_01; + +public class Program { - public class Program + public static void Main() { - public static void Main() - { - #region INCLUDE - DateTime dateTime = new DateTime(); + #region INCLUDE + DateTime dateTime = new DateTime(); - Type type = dateTime.GetType(); - foreach( - System.Reflection.PropertyInfo property in - type.GetProperties()) - { - Console.WriteLine(property.Name); - } - #endregion INCLUDE + Type type = dateTime.GetType(); + foreach( + System.Reflection.PropertyInfo property in + type.GetProperties()) + { + Console.WriteLine(property.Name); } + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter18/Listing18.02.UsingTypeofToCreateASystem.TypeInstance.cs b/src/Chapter18/Listing18.02.UsingTypeofToCreateASystem.TypeInstance.cs index 5aed188cf..a7eed6f04 100644 --- a/src/Chapter18/Listing18.02.UsingTypeofToCreateASystem.TypeInstance.cs +++ b/src/Chapter18/Listing18.02.UsingTypeofToCreateASystem.TypeInstance.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_02; + +using System; +#region INCLUDE +using System.Diagnostics; +#region EXCLUDE +public class Program { - using System; - #region INCLUDE - using System.Diagnostics; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - ThreadPriorityLevel priority; - priority = (ThreadPriorityLevel)Enum.Parse( - typeof(ThreadPriorityLevel), "Idle"); - //... - #endregion INCLUDE - } + #endregion EXCLUDE + ThreadPriorityLevel priority; + priority = (ThreadPriorityLevel)Enum.Parse( + typeof(ThreadPriorityLevel), "Idle"); + //... + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter18/Listing18.03.DynamicallyInvokingAMember.cs b/src/Chapter18/Listing18.03.DynamicallyInvokingAMember.cs index 6fd4ddef2..27491554c 100644 --- a/src/Chapter18/Listing18.03.DynamicallyInvokingAMember.cs +++ b/src/Chapter18/Listing18.03.DynamicallyInvokingAMember.cs @@ -1,160 +1,159 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_03 -{ - #region INCLUDE - using System; - using System.Diagnostics; - using System.IO; - using System.Reflection; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_03; + +#region INCLUDE +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; - public partial class Program +public partial class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) + CommandLineInfo commandLine = new CommandLineInfo(); + if(!CommandLineHandler.TryParse( + args, commandLine, out string? errorMessage)) { - CommandLineInfo commandLine = new CommandLineInfo(); - if(!CommandLineHandler.TryParse( - args, commandLine, out string? errorMessage)) - { - Console.WriteLine(errorMessage); - DisplayHelp(); - } - else if (commandLine.Help || string.IsNullOrWhiteSpace(commandLine.Out)) - { - DisplayHelp(); - } - else - { - if(commandLine.Priority != - ProcessPriorityClass.Normal) - { - // Change thread priority - } - #region EXCLUDE - Console.WriteLine( - @$"Running { - Path.GetFileName(Environment.GetCommandLineArgs()[0])} /Out:{ - commandLine.Out} /Priority:{ - commandLine.Priority}"); - - #endregion EXCLUDE - } + Console.WriteLine(errorMessage); + DisplayHelp(); + } + else if (commandLine.Help || string.IsNullOrWhiteSpace(commandLine.Out)) + { + DisplayHelp(); } - - private static void DisplayHelp() + else { - // Display the command-line help. + if(commandLine.Priority != + ProcessPriorityClass.Normal) + { + // Change thread priority + } + #region EXCLUDE Console.WriteLine( - "Compress.exe /Out:< file name > /Help " - + "/Priority:RealTime | High | " - + "AboveNormal | Normal | BelowNormal | Idle"); + @$"Running { + Path.GetFileName(Environment.GetCommandLineArgs()[0])} /Out:{ + commandLine.Out} /Priority:{ + commandLine.Priority}"); + #endregion EXCLUDE } } - public partial class Program + private static void DisplayHelp() { - private class CommandLineInfo - { - public bool Help { get; set; } + // Display the command-line help. + Console.WriteLine( + "Compress.exe /Out:< file name > /Help " + + "/Priority:RealTime | High | " + + "AboveNormal | Normal | BelowNormal | Idle"); - public string? Out { get; set; } + } +} - public ProcessPriorityClass Priority { get; set; } - = ProcessPriorityClass.Normal; - } +public partial class Program +{ + private class CommandLineInfo + { + public bool Help { get; set; } + public string? Out { get; set; } + + public ProcessPriorityClass Priority { get; set; } + = ProcessPriorityClass.Normal; } - public class CommandLineHandler +} + +public class CommandLineHandler +{ + public static void Parse(string[] args, object commandLine) { - public static void Parse(string[] args, object commandLine) + if (!TryParse(args, commandLine, out string? errorMessage)) { - if (!TryParse(args, commandLine, out string? errorMessage)) - { - throw new InvalidOperationException(errorMessage); - } + throw new InvalidOperationException(errorMessage); } + } - public static bool TryParse(string[] args, object commandLine, - out string? errorMessage) + public static bool TryParse(string[] args, object commandLine, + out string? errorMessage) + { + bool success = false; + errorMessage = null; + foreach(string arg in args) { - bool success = false; - errorMessage = null; - foreach(string arg in args) + string option; + if(arg[0] == '/' || arg[0] == '-') { - string option; - if(arg[0] == '/' || arg[0] == '-') - { - string[] optionParts = arg.Split( - new char[] { ':' }, 2); + string[] optionParts = arg.Split( + new char[] { ':' }, 2); - // Remove the slash|dash - option = optionParts[0].Remove(0, 1); - #region HIGHLIGHT - PropertyInfo? property = - commandLine.GetType().GetProperty(option, - BindingFlags.IgnoreCase | - BindingFlags.Instance | - BindingFlags.Public); - if(property != null) + // Remove the slash|dash + option = optionParts[0].Remove(0, 1); + #region HIGHLIGHT + PropertyInfo? property = + commandLine.GetType().GetProperty(option, + BindingFlags.IgnoreCase | + BindingFlags.Instance | + BindingFlags.Public); + if(property != null) + { + if(property.PropertyType == typeof(bool)) { - if(property.PropertyType == typeof(bool)) - { - // Last parameters for handling indexers - property.SetValue( - commandLine, true, null); - success = true; - } - else if( - property.PropertyType == typeof(string)) + // Last parameters for handling indexers + property.SetValue( + commandLine, true, null); + success = true; + } + else if( + property.PropertyType == typeof(string)) + { + property.SetValue( + commandLine, optionParts[1], null); + success = true; + } + else if ( + // property.PropertyType.IsEnum also available + property.PropertyType == + typeof(ProcessPriorityClass)) + { + try { - property.SetValue( - commandLine, optionParts[1], null); + property.SetValue(commandLine, + Enum.Parse( + typeof(ProcessPriorityClass), + optionParts[1], true), + null); success = true; } - else if ( - // property.PropertyType.IsEnum also available - property.PropertyType == - typeof(ProcessPriorityClass)) - { - try - { - property.SetValue(commandLine, - Enum.Parse( - typeof(ProcessPriorityClass), - optionParts[1], true), - null); - success = true; - } - #endregion HIGHLIGHT - catch (ArgumentException) - { - success = false; - errorMessage = - $@"The option '{ - optionParts[1] - }' is invalid for '{ - option }'"; - } - } - else + #endregion HIGHLIGHT + catch (ArgumentException) { success = false; - errorMessage = - $@"Data type '{ - property.PropertyType }' on { - commandLine.GetType() } is not supported."; + errorMessage = + $@"The option '{ + optionParts[1] + }' is invalid for '{ + option }'"; } } else { success = false; errorMessage = - $"Option '{ option }' is not supported."; + $@"Data type '{ + property.PropertyType }' on { + commandLine.GetType() } is not supported."; } } + else + { + success = false; + errorMessage = + $"Option '{ option }' is not supported."; + } } - return success; } + return success; } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.04.DeclaringTheStackClass.cs b/src/Chapter18/Listing18.04.DeclaringTheStackClass.cs index bbd7bd09b..959530ee2 100644 --- a/src/Chapter18/Listing18.04.DeclaringTheStackClass.cs +++ b/src/Chapter18/Listing18.04.DeclaringTheStackClass.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_04; + +using System; +#region INCLUDE +public class Stack { - using System; - #region INCLUDE - public class Stack + //... + public void Add(T i) { //... - public void Add(T i) - { - //... - Type t = typeof(T); - //... - } + Type t = typeof(T); //... } - #endregion INCLUDE -} \ No newline at end of file + //... +} +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.05.ReflectionWithGenerics.cs b/src/Chapter18/Listing18.05.ReflectionWithGenerics.cs index 57c4523e4..bf98adbcc 100644 --- a/src/Chapter18/Listing18.05.ReflectionWithGenerics.cs +++ b/src/Chapter18/Listing18.05.ReflectionWithGenerics.cs @@ -1,21 +1,20 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_05 -{ - #region INCLUDE - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_05; + +#region INCLUDE +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Type type; - type = typeof(System.Nullable<>); - Console.WriteLine(type.ContainsGenericParameters); - Console.WriteLine(type.IsGenericType); + Type type; + type = typeof(System.Nullable<>); + Console.WriteLine(type.ContainsGenericParameters); + Console.WriteLine(type.IsGenericType); - type = typeof(System.Nullable); - Console.WriteLine(type.ContainsGenericParameters); - Console.WriteLine(type.IsGenericType); - } + type = typeof(System.Nullable); + Console.WriteLine(type.ContainsGenericParameters); + Console.WriteLine(type.IsGenericType); } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.06.UsingReflectionWithGenericTypes.cs b/src/Chapter18/Listing18.06.UsingReflectionWithGenericTypes.cs index 3e41a0dd9..306c060dd 100644 --- a/src/Chapter18/Listing18.06.UsingReflectionWithGenericTypes.cs +++ b/src/Chapter18/Listing18.06.UsingReflectionWithGenericTypes.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_06 -{ - #region INCLUDE - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_06; + +#region INCLUDE +using System; +using System.Collections.Generic; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Stack s = new Stack(); + Stack s = new Stack(); - Type t = s.GetType(); + Type t = s.GetType(); - foreach(Type type in t.GetGenericArguments()) - { - System.Console.WriteLine( - "Type parameter: " + type.FullName); - } - //... + foreach(Type type in t.GetGenericArguments()) + { + System.Console.WriteLine( + "Type parameter: " + type.FullName); } + //... } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.07.DynamicallyInvokingAMember.cs b/src/Chapter18/Listing18.07.DynamicallyInvokingAMember.cs index cc5625817..2c5e773f8 100644 --- a/src/Chapter18/Listing18.07.DynamicallyInvokingAMember.cs +++ b/src/Chapter18/Listing18.07.DynamicallyInvokingAMember.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_07 -{ - #region INCLUDE - using System.ComponentModel; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_07; + +#region INCLUDE +using System.ComponentModel; - public class Person : INotifyPropertyChanged +public class Person : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + public Person(string name) { - public event PropertyChangedEventHandler? PropertyChanged; - public Person(string name) - { - Name = name; - } - private string _Name = string.Empty; - public string Name + Name = name; + } + private string _Name = string.Empty; + public string Name + { + get { return _Name; } + set { - get { return _Name; } - set + if (_Name != value) { - if (_Name != value) - { - _Name = value; - PropertyChanged?.Invoke( - this, - #region HIGHLIGHT - new PropertyChangedEventArgs( - nameof(Name))); - #endregion HIGHLIGHT - } + _Name = value; + PropertyChanged?.Invoke( + this, + #region HIGHLIGHT + new PropertyChangedEventArgs( + nameof(Name))); + #endregion HIGHLIGHT } } - // ... } - #endregion INCLUDE -} \ No newline at end of file + // ... +} +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.08.DecoratingAPropertyWithAnAttribute.cs b/src/Chapter18/Listing18.08.DecoratingAPropertyWithAnAttribute.cs index 9d618405e..72e2c2acc 100644 --- a/src/Chapter18/Listing18.08.DecoratingAPropertyWithAnAttribute.cs +++ b/src/Chapter18/Listing18.08.DecoratingAPropertyWithAnAttribute.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_08; + +using System; +#region INCLUDE +public class CommandLineInfo { - using System; - #region INCLUDE - public class CommandLineInfo - { - #region HIGHLIGHT - [CommandLineSwitchAlias("?")] - #endregion HIGHLIGHT - public bool Help { get; set; } + #region HIGHLIGHT + [CommandLineSwitchAlias("?")] + #endregion HIGHLIGHT + public bool Help { get; set; } - #region HIGHLIGHT - [CommandLineSwitchRequired] - #endregion HIGHLIGHT - public string? Out { get; set; } + #region HIGHLIGHT + [CommandLineSwitchRequired] + #endregion HIGHLIGHT + public string? Out { get; set; } - public System.Diagnostics.ProcessPriorityClass Priority - { get; set; } = - System.Diagnostics.ProcessPriorityClass.Normal; - } - #endregion INCLUDE - // Disabling warning since it is not implemented or shown in manuscript + public System.Diagnostics.ProcessPriorityClass Priority + { get; set; } = + System.Diagnostics.ProcessPriorityClass.Normal; +} +#endregion INCLUDE +// Disabling warning since it is not implemented or shown in manuscript #pragma warning disable CA1018 // Mark attributes with AttributeUsageAttribute - internal class CommandLineSwitchRequiredAttribute : Attribute - { - //not implemented - } +internal class CommandLineSwitchRequiredAttribute : Attribute +{ + //not implemented +} - internal class CommandLineSwitchAliasAttribute : Attribute +internal class CommandLineSwitchAliasAttribute : Attribute +{ + public CommandLineSwitchAliasAttribute(string _) { - public CommandLineSwitchAliasAttribute(string _) - { - //not implemented - } + //not implemented } } \ No newline at end of file diff --git a/src/Chapter18/Listing18.09.DecoratingAPropertyWithMultipleAttributes.cs b/src/Chapter18/Listing18.09.DecoratingAPropertyWithMultipleAttributes.cs index f7160c58f..3287dc05a 100644 --- a/src/Chapter18/Listing18.09.DecoratingAPropertyWithMultipleAttributes.cs +++ b/src/Chapter18/Listing18.09.DecoratingAPropertyWithMultipleAttributes.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_09 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_09; - public class CommandLineInfo - { - [CommandLineSwitchAlias("?")] - public bool Help { get; set; } +using System; - //Two Ways to do it - //[CommandLineSwitchRequired] - //[CommandLineSwitchAlias("FileName")] - #region INCLUDE - [CommandLineSwitchRequired, - CommandLineSwitchAlias("FileName")] - public string? Out { get; set; } +public class CommandLineInfo +{ + [CommandLineSwitchAlias("?")] + public bool Help { get; set; } - public System.Diagnostics.ProcessPriorityClass Priority - { get; set; } = - System.Diagnostics.ProcessPriorityClass.Normal; - } - #endregion INCLUDE + //Two Ways to do it + //[CommandLineSwitchRequired] + //[CommandLineSwitchAlias("FileName")] + #region INCLUDE + [CommandLineSwitchRequired, + CommandLineSwitchAlias("FileName")] + public string? Out { get; set; } - // Disabling warning since it is not implemented or shown in manuscript + public System.Diagnostics.ProcessPriorityClass Priority + { get; set; } = + System.Diagnostics.ProcessPriorityClass.Normal; +} +#endregion INCLUDE + +// Disabling warning since it is not implemented or shown in manuscript #pragma warning disable CA1018 // Mark attributes with AttributeUsageAttribute - internal class CommandLineSwitchRequiredAttribute : Attribute - { - //not implimented - } +internal class CommandLineSwitchRequiredAttribute : Attribute +{ + //not implimented +} - internal class CommandLineSwitchAliasAttribute : Attribute +internal class CommandLineSwitchAliasAttribute : Attribute +{ + public CommandLineSwitchAliasAttribute(string _) { - public CommandLineSwitchAliasAttribute(string _) - { - //not implimented - } + //not implimented } } diff --git a/src/Chapter18/Listing18.11.SpecifyingAReturnAttribute.cs b/src/Chapter18/Listing18.11.SpecifyingAReturnAttribute.cs index 9e06f5c14..195acb721 100644 --- a/src/Chapter18/Listing18.11.SpecifyingAReturnAttribute.cs +++ b/src/Chapter18/Listing18.11.SpecifyingAReturnAttribute.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_11; + +public class Program { - public class Program - { #pragma warning disable CA1822 // Mark members as static - #region INCLUDE - [return: Description( - "Returns true if the object is in a valid state.")] - public bool IsValid() - { - // ... - return true; - } - #endregion INCLUDE -#pragma warning restore CA1822 // Mark members as static + #region INCLUDE + [return: Description( + "Returns true if the object is in a valid state.")] + public bool IsValid() + { + // ... + return true; } + #endregion INCLUDE +#pragma warning restore CA1822 // Mark members as static +} - public class DescriptionAttribute : Attribute - { - private readonly string _Description; - public string Description { get { return _Description; } } +public class DescriptionAttribute : Attribute +{ + private readonly string _Description; + public string Description { get { return _Description; } } - public DescriptionAttribute(string description) - { - this._Description = description; - } + public DescriptionAttribute(string description) + { + this._Description = description; } } \ No newline at end of file diff --git a/src/Chapter18/Listing18.12.csprojMockFileForResequencingListings.Placeholder.cs b/src/Chapter18/Listing18.12.csprojMockFileForResequencingListings.Placeholder.cs index 1a68f4a48..6a5d1153e 100644 --- a/src/Chapter18/Listing18.12.csprojMockFileForResequencingListings.Placeholder.cs +++ b/src/Chapter18/Listing18.12.csprojMockFileForResequencingListings.Placeholder.cs @@ -1,6 +1,5 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_12 -{ +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_12; - //Allows for the csproj file listing example to be accounted for when resequencing listings. just rename this - // file with respect to where the csproj file examples should be placed. -} + +//Allows for the csproj file listing example to be accounted for when resequencing listings. just rename this +// file with respect to where the csproj file examples should be placed. diff --git a/src/Chapter18/Listing18.13.DefiningACustomAttribute.cs b/src/Chapter18/Listing18.13.DefiningACustomAttribute.cs index 7808c1639..a76ffdbcf 100644 --- a/src/Chapter18/Listing18.13.DefiningACustomAttribute.cs +++ b/src/Chapter18/Listing18.13.DefiningACustomAttribute.cs @@ -1,9 +1,8 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_13; + +using System; +#region INCLUDE +public class CommandLineSwitchRequiredAttribute : Attribute { - using System; - #region INCLUDE - public class CommandLineSwitchRequiredAttribute : Attribute - { - } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.14.RetrievingACustomAttribute.cs b/src/Chapter18/Listing18.14.RetrievingACustomAttribute.cs index b69acb472..7d460e33d 100644 --- a/src/Chapter18/Listing18.14.RetrievingACustomAttribute.cs +++ b/src/Chapter18/Listing18.14.RetrievingACustomAttribute.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_14 -{ - #region INCLUDE - using System; - using System.Reflection; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_14; + +#region INCLUDE +using System; +using System.Reflection; +using System.Collections.Generic; - public class CommandLineSwitchRequiredAttribute : Attribute +public class CommandLineSwitchRequiredAttribute : Attribute +{ + public static string[] GetMissingRequiredOptions( + object commandLine) { - public static string[] GetMissingRequiredOptions( - object commandLine) - { - List missingOptions = new List(); - PropertyInfo[] properties = - commandLine.GetType().GetProperties(); + List missingOptions = new List(); + PropertyInfo[] properties = + commandLine.GetType().GetProperties(); - foreach(PropertyInfo property in properties) + foreach(PropertyInfo property in properties) + { + Attribute[] attributes = + (Attribute[])property.GetCustomAttributes( + typeof(CommandLineSwitchRequiredAttribute), + false); + if (attributes.Length > 0 && + property.GetValue(commandLine, null) == null) { - Attribute[] attributes = - (Attribute[])property.GetCustomAttributes( - typeof(CommandLineSwitchRequiredAttribute), - false); - if (attributes.Length > 0 && - property.GetValue(commandLine, null) == null) - { - missingOptions.Add(property.Name); - } + missingOptions.Add(property.Name); } - return missingOptions.ToArray(); } + return missingOptions.ToArray(); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.15.ProvidingAnAttributeConstructor.cs b/src/Chapter18/Listing18.15.ProvidingAnAttributeConstructor.cs index fe37b4b83..2aff5b440 100644 --- a/src/Chapter18/Listing18.15.ProvidingAnAttributeConstructor.cs +++ b/src/Chapter18/Listing18.15.ProvidingAnAttributeConstructor.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_15; + +using System; +#region INCLUDE +public class CommandLineSwitchAliasAttribute : Attribute { - using System; - #region INCLUDE - public class CommandLineSwitchAliasAttribute : Attribute + #region HIGHLIGHT + public CommandLineSwitchAliasAttribute(string alias) { - #region HIGHLIGHT - public CommandLineSwitchAliasAttribute(string alias) - { - Alias = alias; - } - #endregion HIGHLIGHT - public string Alias { get; } + Alias = alias; } - public class CommandLineInfo - { - #region HIGHLIGHT - [CommandLineSwitchAlias("?")] - #endregion HIGHLIGHT - public bool Help { get; set; } + #endregion HIGHLIGHT + public string Alias { get; } +} +public class CommandLineInfo +{ + #region HIGHLIGHT + [CommandLineSwitchAlias("?")] + #endregion HIGHLIGHT + public bool Help { get; set; } - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.16.RetrievingASpecificAttributeAndCheckingItsInitialization.cs b/src/Chapter18/Listing18.16.RetrievingASpecificAttributeAndCheckingItsInitialization.cs index d5262e92c..3edeabff0 100644 --- a/src/Chapter18/Listing18.16.RetrievingASpecificAttributeAndCheckingItsInitialization.cs +++ b/src/Chapter18/Listing18.16.RetrievingASpecificAttributeAndCheckingItsInitialization.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_16 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_15; - using System; - using System.Reflection; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_16; + +using AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_15; +using System; +using System.Reflection; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region INCLUDE + PropertyInfo property = + typeof(CommandLineInfo).GetProperty("Help")!; + CommandLineSwitchAliasAttribute? attribute = + (CommandLineSwitchAliasAttribute?) + property.GetCustomAttribute( + typeof(CommandLineSwitchAliasAttribute), false); + if(attribute?.Alias == "?") { - #region INCLUDE - PropertyInfo property = - typeof(CommandLineInfo).GetProperty("Help")!; - CommandLineSwitchAliasAttribute? attribute = - (CommandLineSwitchAliasAttribute?) - property.GetCustomAttribute( - typeof(CommandLineSwitchAliasAttribute), false); - if(attribute?.Alias == "?") - { - Console.WriteLine("Help(?)"); - }; - #endregion INCLUDE - } + Console.WriteLine("Help(?)"); + }; + #endregion INCLUDE } } diff --git a/src/Chapter18/Listing18.17.RetrievingCustomAttributeInstances.cs b/src/Chapter18/Listing18.17.RetrievingCustomAttributeInstances.cs index 13dfb26fb..1a9f18f89 100644 --- a/src/Chapter18/Listing18.17.RetrievingCustomAttributeInstances.cs +++ b/src/Chapter18/Listing18.17.RetrievingCustomAttributeInstances.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_17 -{ - #region INCLUDE - using System; - using System.Reflection; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_17; + +#region INCLUDE +using System; +using System.Reflection; +using System.Collections.Generic; - public class CommandLineSwitchAliasAttribute : Attribute +public class CommandLineSwitchAliasAttribute : Attribute +{ + public CommandLineSwitchAliasAttribute(string alias) { - public CommandLineSwitchAliasAttribute(string alias) - { - Alias = alias; - } + Alias = alias; + } - public string Alias { get; set; } + public string Alias { get; set; } - public static Dictionary GetSwitches( - object commandLine) - { - PropertyInfo[] properties; - Dictionary options = - new Dictionary(); + public static Dictionary GetSwitches( + object commandLine) + { + PropertyInfo[] properties; + Dictionary options = + new Dictionary(); - properties = commandLine.GetType().GetProperties( - BindingFlags.Public | BindingFlags.Instance); - foreach(PropertyInfo property in properties) + properties = commandLine.GetType().GetProperties( + BindingFlags.Public | BindingFlags.Instance); + foreach(PropertyInfo property in properties) + { + options.Add(property.Name, property); + #region HIGHLIGHT + foreach (CommandLineSwitchAliasAttribute attribute in + property.GetCustomAttributes( + typeof(CommandLineSwitchAliasAttribute), false)) + #endregion HIGHLIGHT { - options.Add(property.Name, property); - #region HIGHLIGHT - foreach (CommandLineSwitchAliasAttribute attribute in - property.GetCustomAttributes( - typeof(CommandLineSwitchAliasAttribute), false)) - #endregion HIGHLIGHT - { - options.Add(attribute.Alias.ToLower(), property); - } + options.Add(attribute.Alias.ToLower(), property); } - return options; } + return options; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.18.UpdatingCommandLineHandler.TryParseToHandleAliases.cs b/src/Chapter18/Listing18.18.UpdatingCommandLineHandler.TryParseToHandleAliases.cs index 77d41ba2b..6ed445628 100644 --- a/src/Chapter18/Listing18.18.UpdatingCommandLineHandler.TryParseToHandleAliases.cs +++ b/src/Chapter18/Listing18.18.UpdatingCommandLineHandler.TryParseToHandleAliases.cs @@ -1,115 +1,114 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_18 -{ - using Listing18_17; - #region INCLUDE - using System; - using System.Reflection; - using System.Collections.Generic; - using System.Diagnostics; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_18; + +using Listing18_17; +#region INCLUDE +using System; +using System.Reflection; +using System.Collections.Generic; +using System.Diagnostics; - public class CommandLineHandler +public class CommandLineHandler +{ + // ... + public static bool TryParse( + string[] args, object commandLine, + out string? errorMessage) { - // ... - public static bool TryParse( - string[] args, object commandLine, - out string? errorMessage) - { - bool success = false; - errorMessage = null; + bool success = false; + errorMessage = null; - #region HIGHLIGHT - Dictionary options = - CommandLineSwitchAliasAttribute.GetSwitches( - commandLine); - #endregion HIGHLIGHT + #region HIGHLIGHT + Dictionary options = + CommandLineSwitchAliasAttribute.GetSwitches( + commandLine); + #endregion HIGHLIGHT - foreach (string arg in args) + foreach (string arg in args) + { + string option; + if(arg[0] == '/' || arg[0] == '-') { - string option; - if(arg[0] == '/' || arg[0] == '-') - { - string[] optionParts = arg.Split( - new char[] { ':' }, 2); - option = optionParts[0].Remove(0, 1).ToLower(); + string[] optionParts = arg.Split( + new char[] { ':' }, 2); + option = optionParts[0].Remove(0, 1).ToLower(); - #region HIGHLIGHT - if (options.TryGetValue(option, out PropertyInfo? property)) - #endregion HIGHLIGHT - { - success = SetOption( - commandLine, property, - optionParts, ref errorMessage); - } - else - { - success = false; - errorMessage = - $"Option '{option}' is not supported."; - } + #region HIGHLIGHT + if (options.TryGetValue(option, out PropertyInfo? property)) + #endregion HIGHLIGHT + { + success = SetOption( + commandLine, property, + optionParts, ref errorMessage); + } + else + { + success = false; + errorMessage = + $"Option '{option}' is not supported."; } } - return success; } + return success; + } + + private static bool SetOption( + object commandLine, PropertyInfo property, + string[] optionParts, ref string? errorMessage) + { + bool success; - private static bool SetOption( - object commandLine, PropertyInfo property, - string[] optionParts, ref string? errorMessage) + if(property.PropertyType == typeof(bool)) + { + // Last parameters for handling indexers + property.SetValue( + commandLine, true, null); + success = true; + } + else { - bool success; - if(property.PropertyType == typeof(bool)) + if (optionParts.Length < 2 + || optionParts[1] == "") + { + // No setting was provided for the switch. + success = false; + errorMessage = + $"You must specify the value for the { property.Name } option."; + } + else if( + property.PropertyType == typeof(string)) { - // Last parameters for handling indexers property.SetValue( - commandLine, true, null); + commandLine, optionParts[1], null); success = true; } + else if( + // property.PropertyType.IsEnum also available + property.PropertyType == + typeof(ProcessPriorityClass)) + { + success = TryParseEnumSwitch( + commandLine, optionParts, + property, ref errorMessage); + } else { - - if (optionParts.Length < 2 - || optionParts[1] == "") - { - // No setting was provided for the switch. - success = false; - errorMessage = - $"You must specify the value for the { property.Name } option."; - } - else if( - property.PropertyType == typeof(string)) - { - property.SetValue( - commandLine, optionParts[1], null); - success = true; - } - else if( - // property.PropertyType.IsEnum also available - property.PropertyType == - typeof(ProcessPriorityClass)) - { - success = TryParseEnumSwitch( - commandLine, optionParts, - property, ref errorMessage); - } - else - { - success = false; - errorMessage = - $@"Data type '{ property.PropertyType.ToString() }' on { - commandLine.GetType().ToString() } is not supported."; - } + success = false; + errorMessage = + $@"Data type '{ property.PropertyType.ToString() }' on { + commandLine.GetType().ToString() } is not supported."; } - return success; } - #endregion INCLUDE + return success; + } + #endregion INCLUDE // Justification: Not fully implemented. #pragma warning disable IDE0060 // Remove unused parameter - private static bool TryParseEnumSwitch( - object commandLine, string[] optionParts, PropertyInfo property, ref string? errorMessage) - { - throw new NotImplementedException(); - } -#pragma warning restore IDE0060 // Remove unused parameter + private static bool TryParseEnumSwitch( + object commandLine, string[] optionParts, PropertyInfo property, ref string? errorMessage) + { + throw new NotImplementedException(); } +#pragma warning restore IDE0060 // Remove unused parameter } diff --git a/src/Chapter18/Listing18.19.RestrictingTheConstructsAnAttributeCanDecorate.cs b/src/Chapter18/Listing18.19.RestrictingTheConstructsAnAttributeCanDecorate.cs index 628ae0783..bcf5342b6 100644 --- a/src/Chapter18/Listing18.19.RestrictingTheConstructsAnAttributeCanDecorate.cs +++ b/src/Chapter18/Listing18.19.RestrictingTheConstructsAnAttributeCanDecorate.cs @@ -1,11 +1,10 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_19; + +using System; +#region INCLUDE +[AttributeUsage(AttributeTargets.Property)] +public class CommandLineSwitchAliasAttribute : Attribute { - using System; - #region INCLUDE - [AttributeUsage(AttributeTargets.Property)] - public class CommandLineSwitchAliasAttribute : Attribute - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.20.AttributeUsageAttributeRestrictingWhereToApplyAnAttribute.cs b/src/Chapter18/Listing18.20.AttributeUsageAttributeRestrictingWhereToApplyAnAttribute.cs index 0eea80c41..606196aa4 100644 --- a/src/Chapter18/Listing18.20.AttributeUsageAttributeRestrictingWhereToApplyAnAttribute.cs +++ b/src/Chapter18/Listing18.20.AttributeUsageAttributeRestrictingWhereToApplyAnAttribute.cs @@ -1,13 +1,12 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_20; + +// Will not compile if uncommented +/* +#region INCLUDE +// ERROR: The attribute usage is restricted to properties +[CommandLineSwitchAlias("?")] +class CommandLineInfo { - // Will not compile if uncommented - /* - #region INCLUDE - // ERROR: The attribute usage is restricted to properties - [CommandLineSwitchAlias("?")] - class CommandLineInfo - { - } - #endregion INCLUDE - */ } +#endregion INCLUDE +*/ diff --git a/src/Chapter18/Listing18.21.LimitingAnAttributesUsageWithAttributeUsageAttribute.cs b/src/Chapter18/Listing18.21.LimitingAnAttributesUsageWithAttributeUsageAttribute.cs index cfdd15d01..42582454c 100644 --- a/src/Chapter18/Listing18.21.LimitingAnAttributesUsageWithAttributeUsageAttribute.cs +++ b/src/Chapter18/Listing18.21.LimitingAnAttributesUsageWithAttributeUsageAttribute.cs @@ -1,15 +1,14 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_21 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_21; + +using System; +#region INCLUDE +// Restrict the attribute to properties and methods +#region HIGHLIGHT +[AttributeUsage( + AttributeTargets.Field | AttributeTargets.Property)] +#endregion HIGHLIGHT +public class CommandLineSwitchAliasAttribute : Attribute { - using System; - #region INCLUDE - // Restrict the attribute to properties and methods - #region HIGHLIGHT - [AttributeUsage( - AttributeTargets.Field | AttributeTargets.Property)] - #endregion HIGHLIGHT - public class CommandLineSwitchAliasAttribute : Attribute - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.22.UsingANamedParameter.cs b/src/Chapter18/Listing18.22.UsingANamedParameter.cs index 6cdc8fea8..38978e639 100644 --- a/src/Chapter18/Listing18.22.UsingANamedParameter.cs +++ b/src/Chapter18/Listing18.22.UsingANamedParameter.cs @@ -1,11 +1,10 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_22; + +using System; +#region INCLUDE +[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] +public class CommandLineSwitchAliasAttribute : Attribute { - using System; - #region INCLUDE - [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] - public class CommandLineSwitchAliasAttribute : Attribute - { - // ... - } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.23.UsingFlagsAttribute.cs b/src/Chapter18/Listing18.23.UsingFlagsAttribute.cs index 829519ff1..3d98bd871 100644 --- a/src/Chapter18/Listing18.23.UsingFlagsAttribute.cs +++ b/src/Chapter18/Listing18.23.UsingFlagsAttribute.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_23 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_23; + +#region INCLUDE +/* +[Flags] +public enun FileAttributes { - #region INCLUDE - /* - [Flags] - public enun FileAttributes - { - ReadOnly = 0x0001, - Hidden = 0x0002, - // ... - } - */ + ReadOnly = 0x0001, + Hidden = 0x0002, + // ... +} +*/ - using System; - using System.IO; +using System; +using System.IO; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - // ... - string fileName = @"enumtest.txt"; - FileInfo file = new FileInfo(fileName); + // ... + string fileName = @"enumtest.txt"; + FileInfo file = new FileInfo(fileName); - file.Attributes = FileAttributes.Hidden | - FileAttributes.ReadOnly; + file.Attributes = FileAttributes.Hidden | + FileAttributes.ReadOnly; - Console.WriteLine("\"{0}\" outputs as \"{1}\"", - file.Attributes.ToString().Replace(",", " |"), - file.Attributes); + Console.WriteLine("\"{0}\" outputs as \"{1}\"", + file.Attributes.ToString().Replace(",", " |"), + file.Attributes); - FileAttributes attributes = - (FileAttributes)Enum.Parse(typeof(FileAttributes), - file.Attributes.ToString()); + FileAttributes attributes = + (FileAttributes)Enum.Parse(typeof(FileAttributes), + file.Attributes.ToString()); - Console.WriteLine(attributes); + Console.WriteLine(attributes); - // ... - } + // ... } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.24.UsingConditionalAttributeToEliminateACall.cs b/src/Chapter18/Listing18.24.UsingConditionalAttributeToEliminateACall.cs index d0d2ae640..2674fb420 100644 --- a/src/Chapter18/Listing18.24.UsingConditionalAttributeToEliminateACall.cs +++ b/src/Chapter18/Listing18.24.UsingConditionalAttributeToEliminateACall.cs @@ -1,33 +1,32 @@ #region INCLUDE #define CONDITION_A #region EXCLUDE -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_24 -{ - #endregion EXCLUDE - using System; - using System.Diagnostics; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_24; + +#endregion EXCLUDE +using System; +using System.Diagnostics; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Console.WriteLine("Begin..."); - MethodA(); - MethodB(); - Console.WriteLine("End..."); - } + Console.WriteLine("Begin..."); + MethodA(); + MethodB(); + Console.WriteLine("End..."); + } - [Conditional("CONDITION_A")] - public static void MethodA() - { - Console.WriteLine("MethodA() executing..."); - } + [Conditional("CONDITION_A")] + public static void MethodA() + { + Console.WriteLine("MethodA() executing..."); + } - [Conditional("CONDITION_B")] - public static void MethodB() - { - Console.WriteLine("MethodB() executing..."); - } + [Conditional("CONDITION_B")] + public static void MethodB() + { + Console.WriteLine("MethodB() executing..."); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.25.UsingObsoleteAttribute.cs b/src/Chapter18/Listing18.25.UsingObsoleteAttribute.cs index c36ad9ddb..8eecc5962 100644 --- a/src/Chapter18/Listing18.25.UsingObsoleteAttribute.cs +++ b/src/Chapter18/Listing18.25.UsingObsoleteAttribute.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_25 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_25; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + public static void Main() { - public static void Main() - { - ObsoleteMethod(); - } + ObsoleteMethod(); + } - [Obsolete] - public static void ObsoleteMethod() - { - } + [Obsolete] + public static void ObsoleteMethod() + { } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter18/Listing18.26.DynamicProgrammingUsingReflection.cs b/src/Chapter18/Listing18.26.DynamicProgrammingUsingReflection.cs index 43c4ee359..ba9c74c1f 100644 --- a/src/Chapter18/Listing18.26.DynamicProgrammingUsingReflection.cs +++ b/src/Chapter18/Listing18.26.DynamicProgrammingUsingReflection.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_26 -{ - #region INCLUDE - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_26; + +#region INCLUDE +using System; - #region EXCLUDE - public class Program +#region EXCLUDE +public class Program +{ + public static void Main() { - public static void Main() + #endregion EXCLUDE + dynamic data = + "Hello! My name is Inigo Montoya"; + Console.WriteLine(data); + data = (double)data.Length; + data = data * 3.5 + 28.6; + if(data == 2.4 + 112 + 26.2) + // The distance (in miles) for the swim, bike, and + // run portions of an Ironman triathlon, respectively + { + Console.WriteLine( + $"{data} makes for a long triathlon."); + } + else { - #endregion EXCLUDE - dynamic data = - "Hello! My name is Inigo Montoya"; - Console.WriteLine(data); - data = (double)data.Length; - data = data * 3.5 + 28.6; - if(data == 2.4 + 112 + 26.2) - // The distance (in miles) for the swim, bike, and - // run portions of an Ironman triathlon, respectively - { - Console.WriteLine( - $"{data} makes for a long triathlon."); - } - else - { - data.NonExistentMethodCallStillCompiles(); - } - // ... - #endregion INCLUDE + data.NonExistentMethodCallStillCompiles(); } + // ... + #endregion INCLUDE } } diff --git a/src/Chapter18/Listing18.27.RuntimeBindingToXMLElementsWithoutDynamic.cs b/src/Chapter18/Listing18.27.RuntimeBindingToXMLElementsWithoutDynamic.cs index 0fa6ecdab..10bbfa80f 100644 --- a/src/Chapter18/Listing18.27.RuntimeBindingToXMLElementsWithoutDynamic.cs +++ b/src/Chapter18/Listing18.27.RuntimeBindingToXMLElementsWithoutDynamic.cs @@ -1,26 +1,25 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_27 -{ - #region INCLUDE - using System; - using System.Linq; - using System.Xml.Linq; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_27; + +#region INCLUDE +using System; +using System.Linq; +using System.Xml.Linq; - #region EXCLUDE - public class Program +#region EXCLUDE +public class Program +{ + public static void Main() { - public static void Main() - { - #endregion EXCLUDE - XElement person = XElement.Parse( - @" + #endregion EXCLUDE + XElement person = XElement.Parse( + @" Inigo Montoya "); - Console.WriteLine($"{ person.Descendants("FirstName").First().Value }" + - $"{ person.Descendants("LastName").First().Value }"); - //... - #endregion INCLUDE - } + Console.WriteLine($"{ person.Descendants("FirstName").First().Value }" + + $"{ person.Descendants("LastName").First().Value }"); + //... + #endregion INCLUDE } } diff --git a/src/Chapter18/Listing18.28.RuntimeBindingToXMLWithDynamics.cs b/src/Chapter18/Listing18.28.RuntimeBindingToXMLWithDynamics.cs index 51a19740c..7e6129900 100644 --- a/src/Chapter18/Listing18.28.RuntimeBindingToXMLWithDynamics.cs +++ b/src/Chapter18/Listing18.28.RuntimeBindingToXMLWithDynamics.cs @@ -1,24 +1,23 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_28 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_28; + +using Listing18_29; +#region INCLUDE +using System; +#region EXCLUDE +public class Program { - using Listing18_29; - #region INCLUDE - using System; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { #endregion EXCLUDE - dynamic person = DynamicXml.Parse( - @" + dynamic person = DynamicXml.Parse( + @" Inigo Montoya "); - Console.WriteLine( - $"{ person.FirstName } { person.LastName }"); - //... - #endregion INCLUDE - } + Console.WriteLine( + $"{ person.FirstName } { person.LastName }"); + //... + #endregion INCLUDE } } diff --git a/src/Chapter18/Listing18.29.ImplementingACustomDynamicObject.cs b/src/Chapter18/Listing18.29.ImplementingACustomDynamicObject.cs index 469e8fbae..61d6ba8ed 100644 --- a/src/Chapter18/Listing18.29.ImplementingACustomDynamicObject.cs +++ b/src/Chapter18/Listing18.29.ImplementingACustomDynamicObject.cs @@ -1,66 +1,65 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_29 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter18.Listing18_29; + +#region INCLUDE +using System.Dynamic; +using System.Linq; +using System.Xml.Linq; + +public class DynamicXml : DynamicObject { - #region INCLUDE - using System.Dynamic; - using System.Linq; - using System.Xml.Linq; + private XElement Element { get; set; } - public class DynamicXml : DynamicObject + public DynamicXml(System.Xml.Linq.XElement element) { - private XElement Element { get; set; } - - public DynamicXml(System.Xml.Linq.XElement element) - { - Element = element; - } + Element = element; + } - public static DynamicXml Parse(string text) - { - return new DynamicXml(XElement.Parse(text)); - } + public static DynamicXml Parse(string text) + { + return new DynamicXml(XElement.Parse(text)); + } - public override bool TryGetMember( - GetMemberBinder binder, out object? result) + public override bool TryGetMember( + GetMemberBinder binder, out object? result) + { + bool success = false; + result = null; + XElement? firstDescendant = + Element.Descendants(binder.Name).FirstOrDefault(); + if(firstDescendant != null) { - bool success = false; - result = null; - XElement? firstDescendant = - Element.Descendants(binder.Name).FirstOrDefault(); - if(firstDescendant != null) + if(firstDescendant.Descendants().Any()) + { + result = new DynamicXml(firstDescendant); + } + else { - if(firstDescendant.Descendants().Any()) - { - result = new DynamicXml(firstDescendant); - } - else - { - result = firstDescendant.Value; - } - success = true; + result = firstDescendant.Value; } - return success; + success = true; } + return success; + } - public override bool TrySetMember( - SetMemberBinder binder, object? value) + public override bool TrySetMember( + SetMemberBinder binder, object? value) + { + bool success = false; + XElement? firstDescendant = + Element.Descendants(binder.Name).FirstOrDefault(); + if(firstDescendant != null) { - bool success = false; - XElement? firstDescendant = - Element.Descendants(binder.Name).FirstOrDefault(); - if(firstDescendant != null) + if(value?.GetType() == typeof(XElement)) + { + firstDescendant.ReplaceWith(value); + } + else { - if(value?.GetType() == typeof(XElement)) - { - firstDescendant.ReplaceWith(value); - } - else - { - firstDescendant.Value = value?.ToString() ?? string.Empty; - } - success = true; + firstDescendant.Value = value?.ToString() ?? string.Empty; } - return success; + success = true; } + return success; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.01.InvokingAnAsynchronousTask.cs b/src/Chapter19/Listing19.01.InvokingAnAsynchronousTask.cs index dfdba231e..a7aa4e3d2 100644 --- a/src/Chapter19/Listing19.01.InvokingAnAsynchronousTask.cs +++ b/src/Chapter19/Listing19.01.InvokingAnAsynchronousTask.cs @@ -1,33 +1,32 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_01 -{ - #region INCLUDE - using System; - #region HIGHLIGHT - using System.Threading.Tasks; - #endregion HIGHLIGHT +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_01; + +#region INCLUDE +using System; +#region HIGHLIGHT +using System.Threading.Tasks; +#endregion HIGHLIGHT - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - const int repetitions = 10000; - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - Task task = Task.Run(() => - { - for(int count = 0; count < repetitions; count++) - { - Console.Write('-'); - } - }); - for(int count = 0; count < repetitions; count++) + const int repetitions = 10000; + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + Task task = Task.Run(() => { - Console.Write('+'); - } - - // Wait until the Task completes - task.Wait(); + for(int count = 0; count < repetitions; count++) + { + Console.Write('-'); + } + }); + for(int count = 0; count < repetitions; count++) + { + Console.Write('+'); } + + // Wait until the Task completes + task.Wait(); } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.02.PollingATask.cs b/src/Chapter19/Listing19.02.PollingATask.cs index a70f3d776..186b31f8e 100644 --- a/src/Chapter19/Listing19.02.PollingATask.cs +++ b/src/Chapter19/Listing19.02.PollingATask.cs @@ -1,70 +1,69 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_02 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_02; + +#region INCLUDE +using System; +using System.Threading.Tasks; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - #region HIGHLIGHT - Task task = - Task.Run( - #endregion HIGHLIGHT - () => PiCalculator.Calculate(100)); + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + #region HIGHLIGHT + Task task = + Task.Run( + #endregion HIGHLIGHT + () => PiCalculator.Calculate(100)); - foreach( - char busySymbol in Utility.BusySymbols()) + foreach( + char busySymbol in Utility.BusySymbols()) + { + if(task.IsCompleted) { - if(task.IsCompleted) - { - Console.Write('\b'); - break; - } - Console.Write(busySymbol); + Console.Write('\b'); + break; } + Console.Write(busySymbol); + } - Console.WriteLine(); + Console.WriteLine(); - #region HIGHLIGHT - Console.WriteLine(task.Result); - #endregion HIGHLIGHT - if (!task.IsCompleted) - { - throw new Exception("Task Should Be Completed"); - } + #region HIGHLIGHT + Console.WriteLine(task.Result); + #endregion HIGHLIGHT + if (!task.IsCompleted) + { + throw new Exception("Task Should Be Completed"); } } - #region EXCLUDE - /* - #endregion EXCLUDE - public class PiCalculator +} +#region EXCLUDE +/* +#endregion EXCLUDE +public class PiCalculator +{ + public static string Calculate(int digits = 100) { - public static string Calculate(int digits = 100) - { - //... - } + //... } - public class Utility +} +public class Utility +{ + public static IEnumerable BusySymbols() { - public static IEnumerable BusySymbols() + string busySymbols = @"-\|/-\|/"; + int next = 0; + while(true) { - string busySymbols = @"-\|/-\|/"; - int next = 0; - while(true) - { - yield return busySymbols[next]; - next = next + 1) % busySymbols.Length; - yield return '\b'; - } + yield return busySymbols[next]; + next = next + 1) % busySymbols.Length; + yield return '\b'; } } - #region EXCLUDE - */ - #endregion EXCLUDE - #endregion INCLUDE -} \ No newline at end of file +} + #region EXCLUDE +*/ +#endregion EXCLUDE +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.03.CallingTaskContinueWith.cs b/src/Chapter19/Listing19.03.CallingTaskContinueWith.cs index 1cca5e0dd..0babbc207 100644 --- a/src/Chapter19/Listing19.03.CallingTaskContinueWith.cs +++ b/src/Chapter19/Listing19.03.CallingTaskContinueWith.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_03 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_03; + +#region INCLUDE +using System; +using System.Threading.Tasks; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - Console.WriteLine("Before"); - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - Task taskA = - Task.Run(() => - Console.WriteLine("Starting...")) - .ContinueWith(antecedent => - Console.WriteLine("Continuing A...")); - Task taskB = taskA.ContinueWith(antecedent => - Console.WriteLine("Continuing B...")); - Task taskC = taskA.ContinueWith(antecedent => - Console.WriteLine("Continuing C...")); - Task.WaitAll(taskB, taskC); - Console.WriteLine("Finished!"); - } + Console.WriteLine("Before"); + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + Task taskA = + Task.Run(() => + Console.WriteLine("Starting...")) + .ContinueWith(antecedent => + Console.WriteLine("Continuing A...")); + Task taskB = taskA.ContinueWith(antecedent => + Console.WriteLine("Continuing B...")); + Task taskC = taskA.ContinueWith(antecedent => + Console.WriteLine("Continuing C...")); + Task.WaitAll(taskB, taskC); + Console.WriteLine("Finished!"); } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.04.RegisteringForNotificationsWithContinueWith.cs b/src/Chapter19/Listing19.04.RegisteringForNotificationsWithContinueWith.cs index 96e883ce1..8334f6fa7 100644 --- a/src/Chapter19/Listing19.04.RegisteringForNotificationsWithContinueWith.cs +++ b/src/Chapter19/Listing19.04.RegisteringForNotificationsWithContinueWith.cs @@ -1,60 +1,59 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_04 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_04; + +#region INCLUDE +using System; +using System.Threading.Tasks; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - Task task = - Task.Run( - () => PiCalculator.Calculate(10)); - Task faultedTask = task.ContinueWith( - (antecedentTask) => + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + Task task = + Task.Run( + () => PiCalculator.Calculate(10)); + Task faultedTask = task.ContinueWith( + (antecedentTask) => + { + if(!antecedentTask.IsFaulted) { - if(!antecedentTask.IsFaulted) - { - throw new Exception("Antecedent Task Should Be Faulted"); - } - Console.WriteLine( - "Task State: Faulted"); - }, - TaskContinuationOptions.OnlyOnFaulted); - - Task canceledTask = task.ContinueWith( - (antecedentTask) => + throw new Exception("Antecedent Task Should Be Faulted"); + } + Console.WriteLine( + "Task State: Faulted"); + }, + TaskContinuationOptions.OnlyOnFaulted); + + Task canceledTask = task.ContinueWith( + (antecedentTask) => + { + if (!antecedentTask.IsCanceled) { - if (!antecedentTask.IsCanceled) - { - throw new Exception("Antecedent Task Should Be Canceled"); - } - Console.WriteLine( - "Task State: Canceled"); - }, - TaskContinuationOptions.OnlyOnCanceled); - - Task completedTask = task.ContinueWith( - (antecedentTask) => + throw new Exception("Antecedent Task Should Be Canceled"); + } + Console.WriteLine( + "Task State: Canceled"); + }, + TaskContinuationOptions.OnlyOnCanceled); + + Task completedTask = task.ContinueWith( + (antecedentTask) => + { + if (!antecedentTask.IsCompleted) { - if (!antecedentTask.IsCompleted) - { - throw new Exception("Antecedent Task Should Be Completed"); - } - Console.WriteLine( - "Task State: Completed"); - }, TaskContinuationOptions. - OnlyOnRanToCompletion); - - completedTask.Wait(); - } + throw new Exception("Antecedent Task Should Be Completed"); + } + Console.WriteLine( + "Task State: Completed"); + }, TaskContinuationOptions. + OnlyOnRanToCompletion); + + completedTask.Wait(); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.05.HandlingATasksUnhandledException.cs b/src/Chapter19/Listing19.05.HandlingATasksUnhandledException.cs index 4551a6d7b..4df35eb96 100644 --- a/src/Chapter19/Listing19.05.HandlingATasksUnhandledException.cs +++ b/src/Chapter19/Listing19.05.HandlingATasksUnhandledException.cs @@ -1,34 +1,33 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_05 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_05; + +#region INCLUDE +using System; +using System.Threading.Tasks; - public static class Program +public static class Program +{ + public static void Main() { - public static void Main() + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + Task task = Task.Run(() => { - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - Task task = Task.Run(() => - { - throw new InvalidOperationException(); - }); + throw new InvalidOperationException(); + }); - try - { - task.Wait(); - } - catch(AggregateException exception) + try + { + task.Wait(); + } + catch(AggregateException exception) + { + exception.Handle(eachException => { - exception.Handle(eachException => - { - Console.WriteLine( - $"ERROR: { eachException.Message }"); - return true; - }); - } + Console.WriteLine( + $"ERROR: { eachException.Message }"); + return true; + }); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.06.ObservingUnhandledExceptionsWithContinueWith.cs b/src/Chapter19/Listing19.06.ObservingUnhandledExceptionsWithContinueWith.cs index cb5b390a0..314e9444a 100644 --- a/src/Chapter19/Listing19.06.ObservingUnhandledExceptionsWithContinueWith.cs +++ b/src/Chapter19/Listing19.06.ObservingUnhandledExceptionsWithContinueWith.cs @@ -1,48 +1,47 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_06 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_06; - public class Program - { - public static void Main() - { - bool parentTaskFaulted = false; - Task task = new Task(() => - { - throw new InvalidOperationException(); - }); - #region HIGHLIGHT - Task continuationTask = task.ContinueWith( - #endregion HIGHLIGHT - (antecedentTask) => - { - parentTaskFaulted = - antecedentTask.IsFaulted; - }, TaskContinuationOptions.OnlyOnFaulted); - task.Start(); - #region HIGHLIGHT - continuationTask.Wait(); - #endregion HIGHLIGHT - if (!parentTaskFaulted) - { - throw new Exception("Parent task should be faulted"); - } - if (!task.IsFaulted) - { - throw new Exception("Task should be faulted"); - } +#region INCLUDE +using System; +using System.Threading.Tasks; - #region HIGHLIGHT - task.Exception!.Handle(eachException => - #endregion HIGHLIGHT +public class Program +{ + public static void Main() + { + bool parentTaskFaulted = false; + Task task = new Task(() => { - Console.WriteLine( - $"ERROR: { eachException.Message }"); - return true; + throw new InvalidOperationException(); }); + #region HIGHLIGHT + Task continuationTask = task.ContinueWith( + #endregion HIGHLIGHT + (antecedentTask) => + { + parentTaskFaulted = + antecedentTask.IsFaulted; + }, TaskContinuationOptions.OnlyOnFaulted); + task.Start(); + #region HIGHLIGHT + continuationTask.Wait(); + #endregion HIGHLIGHT + if (!parentTaskFaulted) + { + throw new Exception("Parent task should be faulted"); + } + if (!task.IsFaulted) + { + throw new Exception("Task should be faulted"); } + + #region HIGHLIGHT + task.Exception!.Handle(eachException => + #endregion HIGHLIGHT + { + Console.WriteLine( + $"ERROR: { eachException.Message }"); + return true; + }); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.07.RegisteringForUnhandledExceptions.cs b/src/Chapter19/Listing19.07.RegisteringForUnhandledExceptions.cs index a9da75fed..4dcf181c5 100644 --- a/src/Chapter19/Listing19.07.RegisteringForUnhandledExceptions.cs +++ b/src/Chapter19/Listing19.07.RegisteringForUnhandledExceptions.cs @@ -1,58 +1,57 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_07; + +#region INCLUDE +using System; +using System.Diagnostics; +using System.Threading; + +public class Program { - #region INCLUDE - using System; - using System.Diagnostics; - using System.Threading; + private static Stopwatch Clock { get; } = new Stopwatch(); - public class Program + public static void Main() { - private static Stopwatch Clock { get; } = new Stopwatch(); - - public static void Main() + try { - try - { - Clock.Start(); - #region HIGHLIGHT - // Register a callback to receive notifications - // of any unhandled exception + Clock.Start(); + #region HIGHLIGHT + // Register a callback to receive notifications + // of any unhandled exception - AppDomain.CurrentDomain.UnhandledException += - (s, e) => - { - Message("Event handler starting"); - Delay(4000); - }; + AppDomain.CurrentDomain.UnhandledException += + (s, e) => + { + Message("Event handler starting"); + Delay(4000); + }; #endregion HIGHLIGHT - Thread thread = new Thread(() => - { - Message("Throwing exception."); - throw new Exception(); - }); - thread.Start(); - - Delay(2000); - } - finally + Thread thread = new Thread(() => { - Message("Finally block running."); - } + Message("Throwing exception."); + throw new Exception(); + }); + thread.Start(); + + Delay(2000); } - - static void Delay(int i) + finally { - Message($"Sleeping for {i} ms"); - Thread.Sleep(i); - Message("Awake"); + Message("Finally block running."); } + } - static void Message(string text) - { - Console.WriteLine("{0}:{1:0000}:{2}", - Thread.CurrentThread.ManagedThreadId, - Clock.ElapsedMilliseconds, text); - } + static void Delay(int i) + { + Message($"Sleeping for {i} ms"); + Thread.Sleep(i); + Message("Awake"); + } + + static void Message(string text) + { + Console.WriteLine("{0}:{1:0000}:{2}", + Thread.CurrentThread.ManagedThreadId, + Clock.ElapsedMilliseconds, text); } -#endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.08.CancelingTaskUsingCancellationToken.cs b/src/Chapter19/Listing19.08.CancelingTaskUsingCancellationToken.cs index 64c1d5ce4..51fd0d653 100644 --- a/src/Chapter19/Listing19.08.CancelingTaskUsingCancellationToken.cs +++ b/src/Chapter19/Listing19.08.CancelingTaskUsingCancellationToken.cs @@ -1,63 +1,62 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_08; + +#region INCLUDE +using System; +using System.Threading; +using System.Threading.Tasks; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public class Program { - #region INCLUDE - using System; - using System.Threading; - using System.Threading.Tasks; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; + public static void Main() + { + string stars = + "*".PadRight(Console.WindowWidth - 1, '*'); + Console.WriteLine("Push ENTER to exit."); + + #region HIGHLIGHT + CancellationTokenSource cancellationTokenSource = + new CancellationTokenSource(); + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + Task task = Task.Run( + () => + WritePi(cancellationTokenSource.Token), + cancellationTokenSource.Token); + #endregion HIGHLIGHT - public class Program + // Wait for the user's input + Console.ReadLine(); + + #region HIGHLIGHT + cancellationTokenSource.Cancel(); + #endregion HIGHLIGHT + Console.WriteLine(stars); + #region HIGHLIGHT + task.Wait(); + #endregion HIGHLIGHT + Console.WriteLine(); + } + + private static void WritePi( + #region HIGHLIGHT + CancellationToken cancellationToken) + #endregion HIGHLIGHT { - public static void Main() - { - string stars = - "*".PadRight(Console.WindowWidth - 1, '*'); - Console.WriteLine("Push ENTER to exit."); - - #region HIGHLIGHT - CancellationTokenSource cancellationTokenSource = - new CancellationTokenSource(); - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - Task task = Task.Run( - () => - WritePi(cancellationTokenSource.Token), - cancellationTokenSource.Token); - #endregion HIGHLIGHT - - // Wait for the user's input - Console.ReadLine(); - - #region HIGHLIGHT - cancellationTokenSource.Cancel(); - #endregion HIGHLIGHT - Console.WriteLine(stars); - #region HIGHLIGHT - task.Wait(); - #endregion HIGHLIGHT - Console.WriteLine(); - } + const int batchSize = 1; + string piSection = string.Empty; + int i = 0; - private static void WritePi( #region HIGHLIGHT - CancellationToken cancellationToken) + while (!cancellationToken.IsCancellationRequested #endregion HIGHLIGHT + || i == int.MaxValue) { - const int batchSize = 1; - string piSection = string.Empty; - int i = 0; - - #region HIGHLIGHT - while (!cancellationToken.IsCancellationRequested - #endregion HIGHLIGHT - || i == int.MaxValue) - { - piSection = PiCalculator.Calculate( - batchSize, (i++) * batchSize); - Console.Write(piSection); - } + piSection = PiCalculator.Calculate( + batchSize, (i++) * batchSize); + Console.Write(piSection); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter19/Listing19.09.UsingTaskRun.cs b/src/Chapter19/Listing19.09.UsingTaskRun.cs index a30ebb6f4..4764d1038 100644 --- a/src/Chapter19/Listing19.09.UsingTaskRun.cs +++ b/src/Chapter19/Listing19.09.UsingTaskRun.cs @@ -1,23 +1,22 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_09 -{ - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_09; + +using System.Threading.Tasks; - public class Program +public class Program +{ + #region INCLUDE + public static Task CalculatePiAsync(int digits) { - #region INCLUDE - public static Task CalculatePiAsync(int digits) - { - return Task.Factory.StartNew( - () => Program.CalculatePi(digits)); - } + return Task.Factory.StartNew( + () => Program.CalculatePi(digits)); + } - private static string CalculatePi(int digits) - { - #region EXCLUDE - return string.Empty; - #endregion EXCLUDEe - } - #endregion INCLUDE + private static string CalculatePi(int digits) + { + #region EXCLUDE + return string.Empty; + #endregion EXCLUDEe } + #endregion INCLUDE } diff --git a/src/Chapter19/Listing19.10.CooperativeLongRunningTasks.cs b/src/Chapter19/Listing19.10.CooperativeLongRunningTasks.cs index 608b8f464..815a9024d 100644 --- a/src/Chapter19/Listing19.10.CooperativeLongRunningTasks.cs +++ b/src/Chapter19/Listing19.10.CooperativeLongRunningTasks.cs @@ -1,58 +1,57 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter19.Listing19_10; + +using System; +using System.Threading; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; +#region INCLUDE +using System.Threading.Tasks; +#region EXCLUDE +public class Program { - using System; - using System.Threading; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; - #region INCLUDE - using System.Threading.Tasks; - #region EXCLUDE - public class Program + public static void Main() { - public static void Main() - { - string stars = - "*".PadRight(Console.WindowWidth - 1, '*'); - Console.WriteLine("Push ENTER to exit."); - - CancellationTokenSource cancellationTokenSource = - new CancellationTokenSource(); - - // Use Task.Factory.StartNew() for - // TPL prior to .NET 4.5 - #endregion EXCLUDE - Task task = Task.Factory.StartNew( - () => - WritePi(cancellationTokenSource.Token), - #region HIGHLIGHT - TaskCreationOptions.LongRunning); - #endregion HIGHLIGHT - - //... - #endregion INCLUDE - - // Wait for the user's input - Console.ReadLine(); - - cancellationTokenSource.Cancel(); - Console.WriteLine(stars); - task.Wait(); - Console.WriteLine(); - } + string stars = + "*".PadRight(Console.WindowWidth - 1, '*'); + Console.WriteLine("Push ENTER to exit."); + + CancellationTokenSource cancellationTokenSource = + new CancellationTokenSource(); + + // Use Task.Factory.StartNew() for + // TPL prior to .NET 4.5 + #endregion EXCLUDE + Task task = Task.Factory.StartNew( + () => + WritePi(cancellationTokenSource.Token), + #region HIGHLIGHT + TaskCreationOptions.LongRunning); + #endregion HIGHLIGHT + + //... + #endregion INCLUDE + + // Wait for the user's input + Console.ReadLine(); + + cancellationTokenSource.Cancel(); + Console.WriteLine(stars); + task.Wait(); + Console.WriteLine(); + } + + private static void WritePi( + CancellationToken cancellationToken) + { + const int batchSize = 1; + string piSection = string.Empty; + int i = 0; - private static void WritePi( - CancellationToken cancellationToken) + while(!cancellationToken.IsCancellationRequested + || i == int.MaxValue) { - const int batchSize = 1; - string piSection = string.Empty; - int i = 0; - - while(!cancellationToken.IsCancellationRequested - || i == int.MaxValue) - { - piSection = PiCalculator.Calculate( - batchSize, (i++) * batchSize); - Console.Write(piSection); - } + piSection = PiCalculator.Calculate( + batchSize, (i++) * batchSize); + Console.Write(piSection); } } } diff --git a/src/Chapter19/Utility.cs b/src/Chapter19/Utility.cs index 4fe5375b0..7757148c0 100644 --- a/src/Chapter19/Utility.cs +++ b/src/Chapter19/Utility.cs @@ -1,39 +1,38 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +using System; +using System.Collections.Generic; +using System.Diagnostics; - static class Utility +static class Utility +{ + public static void DisplayComparison(string title, long synchElapsed, long parallelElapsed) { - public static void DisplayComparison(string title, long synchElapsed, long parallelElapsed) - { - string message = string.Format("synchronous {0} > {1} parallel by {2}%", - synchElapsed, parallelElapsed, - (double)parallelElapsed / (double)synchElapsed); + string message = string.Format("synchronous {0} > {1} parallel by {2}%", + synchElapsed, parallelElapsed, + (double)parallelElapsed / (double)synchElapsed); - Console.WriteLine("\n{0} ({1}:", title, message); - } + Console.WriteLine("\n{0} ({1}:", title, message); + } - public static long MeasureElapsedTime(Action action) - { - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); - action(); - stopwatch.Stop(); - return stopwatch.ElapsedMilliseconds; - } + public static long MeasureElapsedTime(Action action) + { + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + action(); + stopwatch.Stop(); + return stopwatch.ElapsedMilliseconds; + } - public static IEnumerable BusySymbols() + public static IEnumerable BusySymbols() + { + string busySymbols = @"-\|/-\|/"; + int next = 0; + while(true) { - string busySymbols = @"-\|/-\|/"; - int next = 0; - while(true) - { - yield return busySymbols[next]; - next = (++next) % busySymbols.Length; - yield return '\b'; - } + yield return busySymbols[next]; + next = (++next) % busySymbols.Length; + yield return '\b'; } } } diff --git a/src/Chapter20/Listing20.01.SynchronousWebRequestHighLatency.cs b/src/Chapter20/Listing20.01.SynchronousWebRequestHighLatency.cs index eea79c62a..d639b6db6 100644 --- a/src/Chapter20/Listing20.01.SynchronousWebRequestHighLatency.cs +++ b/src/Chapter20/Listing20.01.SynchronousWebRequestHighLatency.cs @@ -1,81 +1,80 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_01; + +#region INCLUDE +using System; +using System.IO; +using System.Net; + +public static class Program { - #region INCLUDE - using System; - using System.IO; - using System.Net; + public const string DefaultUrl = "https://IntelliTect.com"; - public static class Program + public static void Main(string[] args) { - public const string DefaultUrl = "https://IntelliTect.com"; - - public static void Main(string[] args) + if (args.Length == 0) { - if (args.Length == 0) - { - Console.WriteLine("ERROR: No findText argument specified."); - return; - } - string findText = args[0]; + Console.WriteLine("ERROR: No findText argument specified."); + return; + } + string findText = args[0]; - string url = DefaultUrl; - if (args.Length > 1) - { - url = args[1]; - // Ignore additional parameters - } - Console.WriteLine( - $"Searching for '{findText}' at URL '{url}'."); + string url = DefaultUrl; + if (args.Length > 1) + { + url = args[1]; + // Ignore additional parameters + } + Console.WriteLine( + $"Searching for '{findText}' at URL '{url}'."); - Console.WriteLine("Downloading..."); - using WebClient webClient = new WebClient(); - byte[] downloadData = - webClient.DownloadData(url); + Console.WriteLine("Downloading..."); + using WebClient webClient = new WebClient(); + byte[] downloadData = + webClient.DownloadData(url); - Console.WriteLine("Searching..."); - int textOccurrenceCount = CountOccurrences( - downloadData, findText); + Console.WriteLine("Searching..."); + int textOccurrenceCount = CountOccurrences( + downloadData, findText); - Console.WriteLine( - @$"'{findText}' appears { - textOccurrenceCount} times at URL '{url}'."); - } + Console.WriteLine( + @$"'{findText}' appears { + textOccurrenceCount} times at URL '{url}'."); + } - private static int CountOccurrences(byte[] downloadData, string findText) - { - int textOccurrenceCount = 0; + private static int CountOccurrences(byte[] downloadData, string findText) + { + int textOccurrenceCount = 0; - using MemoryStream stream = new MemoryStream(downloadData); - using StreamReader reader = new StreamReader(stream); + using MemoryStream stream = new MemoryStream(downloadData); + using StreamReader reader = new StreamReader(stream); - int findIndex = 0; - int length = 0; - do + int findIndex = 0; + int length = 0; + do + { + char[] data = new char[reader.BaseStream.Length]; + length = reader.Read(data); + for (int i = 0; i < length; i++) { - char[] data = new char[reader.BaseStream.Length]; - length = reader.Read(data); - for (int i = 0; i < length; i++) + if (findText[findIndex] == data[i]) { - if (findText[findIndex] == data[i]) - { - findIndex++; - if (findIndex == findText.Length) - { - // Text was found - textOccurrenceCount++; - findIndex = 0; - } - } - else + findIndex++; + if (findIndex == findText.Length) { + // Text was found + textOccurrenceCount++; findIndex = 0; } } + else + { + findIndex = 0; + } } - while (length != 0); - - return textOccurrenceCount; } + while (length != 0); + + return textOccurrenceCount; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.02.AsynchronousWebRequest.cs b/src/Chapter20/Listing20.02.AsynchronousWebRequest.cs index b56fbe4a2..798f6dbf0 100644 --- a/src/Chapter20/Listing20.02.AsynchronousWebRequest.cs +++ b/src/Chapter20/Listing20.02.AsynchronousWebRequest.cs @@ -1,136 +1,135 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_02 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_02; + +#region INCLUDE +using System; +using System.IO; +using System.Net; +using System.Runtime.ExceptionServices; +using System.Threading.Tasks; + +public static class Program { - #region INCLUDE - using System; - using System.IO; - using System.Net; - using System.Runtime.ExceptionServices; - using System.Threading.Tasks; + public const string DefaultUrl = "https://IntelliTect.com"; - public static class Program + public static void Main(string[] args) { - public const string DefaultUrl = "https://IntelliTect.com"; + if (args.Length == 0) + { + Console.WriteLine("ERROR: No findText argument specified."); + return; + } + string findText = args[0]; - public static void Main(string[] args) + string url = DefaultUrl; + if (args.Length > 1) { - if (args.Length == 0) - { - Console.WriteLine("ERROR: No findText argument specified."); - return; - } - string findText = args[0]; + url = args[1]; + // Ignore additional parameters + } + Console.WriteLine( + $"Searching for '{findText}' at URL '{url}'."); - string url = DefaultUrl; - if (args.Length > 1) + using WebClient webClient = new WebClient(); + Console.Write("Downloading..."); + Task task = webClient.DownloadDataTaskAsync(url) + .ContinueWith(antecedent => { - url = args[1]; - // Ignore additional parameters - } - Console.WriteLine( - $"Searching for '{findText}' at URL '{url}'."); - - using WebClient webClient = new WebClient(); - Console.Write("Downloading..."); - Task task = webClient.DownloadDataTaskAsync(url) - .ContinueWith(antecedent => - { - byte[] downloadData = antecedent.Result; - Console.Write($"{Environment.NewLine}Searching..."); - return CountOccurrencesAsync( - downloadData, findText); - }) - .Unwrap() - .ContinueWith(antecedent => - { - int textOccurrenceCount = antecedent.Result; - Console.WriteLine( - @$"{Environment.NewLine}'{findText}' appears { - textOccurrenceCount} times at URL '{url}'."); + byte[] downloadData = antecedent.Result; + Console.Write($"{Environment.NewLine}Searching..."); + return CountOccurrencesAsync( + downloadData, findText); + }) + .Unwrap() + .ContinueWith(antecedent => + { + int textOccurrenceCount = antecedent.Result; + Console.WriteLine( + @$"{Environment.NewLine}'{findText}' appears { + textOccurrenceCount} times at URL '{url}'."); - }); + }); + try + { + while (!task.Wait(100)) + { + Console.Write("."); + } + } + catch (AggregateException exception) + { + exception = exception.Flatten(); try { - while (!task.Wait(100)) + exception.Handle(innerException => { - Console.Write("."); - } + // Rethrowing rather than using + // if condition on the type + ExceptionDispatchInfo.Capture( + innerException) + .Throw(); + return true; + }); } - catch (AggregateException exception) + catch (WebException) { - exception = exception.Flatten(); - try - { - exception.Handle(innerException => - { - // Rethrowing rather than using - // if condition on the type - ExceptionDispatchInfo.Capture( - innerException) - .Throw(); - return true; - }); - } - catch (WebException) - { - #region EXCLUDE - throw; - #endregion EXCLUDE - } - catch (IOException) - { - #region EXCLUDE - throw; - #endregion EXCLUDE - } - catch (NotSupportedException) - { - #region EXCLUDE - throw; - #endregion EXCLUDE - } + #region EXCLUDE + throw; + #endregion EXCLUDE + } + catch (IOException) + { + #region EXCLUDE + throw; + #endregion EXCLUDE + } + catch (NotSupportedException) + { + #region EXCLUDE + throw; + #endregion EXCLUDE } } + } - private static async Task CountOccurrencesAsync( - byte[] downloadData, string findText) - { - #region EXCLUDE - int textOccurrenceCount = 0; + private static async Task CountOccurrencesAsync( + byte[] downloadData, string findText) + { + #region EXCLUDE + int textOccurrenceCount = 0; - using MemoryStream stream = new MemoryStream(downloadData); - using StreamReader reader = new StreamReader(stream); + using MemoryStream stream = new MemoryStream(downloadData); + using StreamReader reader = new StreamReader(stream); - int findIndex = 0; - int length = 0; - do + int findIndex = 0; + int length = 0; + do + { + char[] data = new char[reader.BaseStream.Length]; + length = await reader.ReadAsync(data); + for (int i = 0; i < length; i++) { - char[] data = new char[reader.BaseStream.Length]; - length = await reader.ReadAsync(data); - for (int i = 0; i < length; i++) + if (findText[findIndex] == data[i]) { - if (findText[findIndex] == data[i]) - { - findIndex++; - if (findIndex == findText.Length) - { - // Text was found - textOccurrenceCount++; - findIndex = 0; - } - } - else + findIndex++; + if (findIndex == findText.Length) { + // Text was found + textOccurrenceCount++; findIndex = 0; } } + else + { + findIndex = 0; + } } - while (length != 0); - - return textOccurrenceCount; - #endregion EXCLUDE } + while (length != 0); + + return textOccurrenceCount; + #endregion EXCLUDE } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.03.AsynchronousHighLatencyUsingTaskAsynchronyPattern.cs b/src/Chapter20/Listing20.03.AsynchronousHighLatencyUsingTaskAsynchronyPattern.cs index 6d67a2e01..87305f6ea 100644 --- a/src/Chapter20/Listing20.03.AsynchronousHighLatencyUsingTaskAsynchronyPattern.cs +++ b/src/Chapter20/Listing20.03.AsynchronousHighLatencyUsingTaskAsynchronyPattern.cs @@ -1,98 +1,97 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_03; + +#region INCLUDE +using System; +using System.IO; +using System.Net; +using System.Threading.Tasks; + +public static class Program { - #region INCLUDE - using System; - using System.IO; - using System.Net; - using System.Threading.Tasks; + public const string DefaultUrl = "https://IntelliTect.com"; - public static class Program + public static async Task Main(string[] args) { - public const string DefaultUrl = "https://IntelliTect.com"; + if (args.Length == 0) + { + Console.WriteLine("ERROR: No findText argument specified."); + return; + } + string findText = args[0]; - public static async Task Main(string[] args) + string url = DefaultUrl; + if (args.Length > 1) { - if (args.Length == 0) - { - Console.WriteLine("ERROR: No findText argument specified."); - return; - } - string findText = args[0]; + url = args[1]; + // Ignore additional parameters + } + Console.WriteLine( + $"Searching for '{findText}' at URL '{url}'."); - string url = DefaultUrl; - if (args.Length > 1) - { - url = args[1]; - // Ignore additional parameters - } - Console.WriteLine( - $"Searching for '{findText}' at URL '{url}'."); + using WebClient webClient = new WebClient(); + Task taskDownload = + webClient.DownloadDataTaskAsync(url); - using WebClient webClient = new WebClient(); - Task taskDownload = - webClient.DownloadDataTaskAsync(url); + Console.Write("Downloading..."); + while (!taskDownload.Wait(100)) + { + Console.Write("."); + } - Console.Write("Downloading..."); - while (!taskDownload.Wait(100)) - { - Console.Write("."); - } + byte[] downloadData = await taskDownload; - byte[] downloadData = await taskDownload; + Task taskSearch = CountOccurrencesAsync( + downloadData, findText); - Task taskSearch = CountOccurrencesAsync( - downloadData, findText); + Console.Write($"{Environment.NewLine}Searching..."); - Console.Write($"{Environment.NewLine}Searching..."); + while (!taskSearch.Wait(100)) + { + Console.Write("."); + } - while (!taskSearch.Wait(100)) - { - Console.Write("."); - } + int textOccurrenceCount = await taskSearch; - int textOccurrenceCount = await taskSearch; + Console.WriteLine( + @$"{Environment.NewLine}'{findText}' appears { + textOccurrenceCount} times at URL '{url}'."); + } - Console.WriteLine( - @$"{Environment.NewLine}'{findText}' appears { - textOccurrenceCount} times at URL '{url}'."); - } + private static async Task CountOccurrencesAsync( + byte[] downloadData, string findText) + { + int textOccurrenceCount = 0; + using MemoryStream stream = new MemoryStream(downloadData); + using StreamReader reader = new StreamReader(stream); - private static async Task CountOccurrencesAsync( - byte[] downloadData, string findText) + int findIndex = 0; + int length = 0; + do { - int textOccurrenceCount = 0; - using MemoryStream stream = new MemoryStream(downloadData); - using StreamReader reader = new StreamReader(stream); - - int findIndex = 0; - int length = 0; - do + char[] data = new char[reader.BaseStream.Length]; + length = await reader.ReadAsync(data); + for (int i = 0; i < length; i++) { - char[] data = new char[reader.BaseStream.Length]; - length = await reader.ReadAsync(data); - for (int i = 0; i < length; i++) + if (findText[findIndex] == data[i]) { - if (findText[findIndex] == data[i]) - { - findIndex++; - if (findIndex == findText.Length) - { - // Text was found - textOccurrenceCount++; - findIndex = 0; - } - } - else + findIndex++; + if (findIndex == findText.Length) { + // Text was found + textOccurrenceCount++; findIndex = 0; } } + else + { + findIndex = 0; + } } - while (length != 0); - - return textOccurrenceCount; } + while (length != 0); + + return textOccurrenceCount; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.04.ValueTaskAsyncReturn.cs b/src/Chapter20/Listing20.04.ValueTaskAsyncReturn.cs index 73b01d86e..87d1eede2 100644 --- a/src/Chapter20/Listing20.04.ValueTaskAsyncReturn.cs +++ b/src/Chapter20/Listing20.04.ValueTaskAsyncReturn.cs @@ -1,59 +1,58 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_04; + +#region INCLUDE +using System.IO; +using System.Text; +using System.Threading.Tasks; + +public static class Program { - #region INCLUDE - using System.IO; - using System.Text; - using System.Threading.Tasks; + public static async ValueTask CompressAsync(byte[] buffer) + { + if (buffer.Length == 0) + { + return buffer; + } + using MemoryStream memoryStream = new MemoryStream(); + using System.IO.Compression.GZipStream gZipStream = + new System.IO.Compression.GZipStream( + memoryStream, + System.IO.Compression.CompressionMode.Compress); + await gZipStream.WriteAsync(buffer.AsMemory(0, buffer.Length)); - public static class Program + return memoryStream.ToArray(); + } + #region EXCLUDE + + public static string UnZip(string value) { - public static async ValueTask CompressAsync(byte[] buffer) + //Transform string into byte[] + byte[] byteArray = new byte[value.Length]; + int index = 0; + foreach (char item in value.ToCharArray()) { - if (buffer.Length == 0) - { - return buffer; - } - using MemoryStream memoryStream = new MemoryStream(); - using System.IO.Compression.GZipStream gZipStream = - new System.IO.Compression.GZipStream( - memoryStream, - System.IO.Compression.CompressionMode.Compress); - await gZipStream.WriteAsync(buffer.AsMemory(0, buffer.Length)); - - return memoryStream.ToArray(); + byteArray[index++] = (byte)item; } - #region EXCLUDE - public static string UnZip(string value) + using MemoryStream memoryStream = new MemoryStream(byteArray); + using System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream, + System.IO.Compression.CompressionMode.Decompress); + + byteArray = new byte[byteArray.Length]; + + //Decompress + int bytesRead = gZipStream.Read(byteArray, 0, byteArray.Length); + + //Transform byte[] unzip data to string + StringBuilder data = new System.Text.StringBuilder(bytesRead); + //Read the number of bytes GZipStream red and do not a for each bytes in + //resultByteArray + for (int i = 0; i < bytesRead; i++) { - //Transform string into byte[] - byte[] byteArray = new byte[value.Length]; - int index = 0; - foreach (char item in value.ToCharArray()) - { - byteArray[index++] = (byte)item; - } - - using MemoryStream memoryStream = new MemoryStream(byteArray); - using System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream, - System.IO.Compression.CompressionMode.Decompress); - - byteArray = new byte[byteArray.Length]; - - //Decompress - int bytesRead = gZipStream.Read(byteArray, 0, byteArray.Length); - - //Transform byte[] unzip data to string - StringBuilder data = new System.Text.StringBuilder(bytesRead); - //Read the number of bytes GZipStream red and do not a for each bytes in - //resultByteArray - for (int i = 0; i < bytesRead; i++) - { - data.Append((char)byteArray[i]); - } - return data.ToString(); + data.Append((char)byteArray[i]); } - #endregion EXCLUDE + return data.ToString(); } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.05.AwaitStatement.cs b/src/Chapter20/Listing20.05.AwaitStatement.cs index b907d2cc0..a72aaaa51 100644 --- a/src/Chapter20/Listing20.05.AwaitStatement.cs +++ b/src/Chapter20/Listing20.05.AwaitStatement.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_05; + +using System.Threading.Tasks; + +public class Program { - using System.Threading.Tasks; + #region INCLUDE + public async Task DoStuffAsync() + { + await DoSomethingAsync(); + await DoSomethingElseAsync(); + return await GetAnIntegerAsync() + 1; + } + #endregion INCLUDE - public class Program + public Task GetAnIntegerAsync() { - #region INCLUDE - public async Task DoStuffAsync() - { - await DoSomethingAsync(); - await DoSomethingElseAsync(); - return await GetAnIntegerAsync() + 1; - } - #endregion INCLUDE - - public Task GetAnIntegerAsync() - { - // ... - - throw new System.NotImplementedException(); - } - - public Task DoSomethingElseAsync() - { - // ... - - throw new System.NotImplementedException(); - } - - public Task DoSomethingAsync() - { - // ... - - throw new System.NotImplementedException(); - } + // ... + + throw new System.NotImplementedException(); + } + + public Task DoSomethingElseAsync() + { + // ... + + throw new System.NotImplementedException(); + } + + public Task DoSomethingAsync() + { + // ... + + throw new System.NotImplementedException(); } } diff --git a/src/Chapter20/Listing20.06.AsynchronousStreams.cs b/src/Chapter20/Listing20.06.AsynchronousStreams.cs index b46d65ce2..6ef885b6c 100644 --- a/src/Chapter20/Listing20.06.AsynchronousStreams.cs +++ b/src/Chapter20/Listing20.06.AsynchronousStreams.cs @@ -1,98 +1,97 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_06 -{ - using System; - #region INCLUDE - using System.IO; - using System.Linq; - using System.Threading.Tasks; - using System.Collections.Generic; - using System.Threading; - using System.Runtime.CompilerServices; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_06; + +using System; +#region INCLUDE +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading; +using System.Runtime.CompilerServices; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; - public static class Program +public static class Program +{ + public static async void Main(params string[] args) { - public static async void Main(params string[] args) + string directoryPath = Directory.GetCurrentDirectory(); + string searchPattern = "*"; + #region EXCLUDE + switch (args?.Length) { - string directoryPath = Directory.GetCurrentDirectory(); - string searchPattern = "*"; - #region EXCLUDE - switch (args?.Length) - { - case 1: - directoryPath = args[0]; - break; - case 2: - searchPattern = args[1]; - break; - default: - DisplayHelp(); - break; - } - #endregion EXCLUDE - using Cryptographer cryptographer = new Cryptographer(); + case 1: + directoryPath = args[0]; + break; + case 2: + searchPattern = args[1]; + break; + default: + DisplayHelp(); + break; + } + #endregion EXCLUDE + using Cryptographer cryptographer = new Cryptographer(); - IEnumerable files = Directory.EnumerateFiles( - directoryPath, searchPattern); + IEnumerable files = Directory.EnumerateFiles( + directoryPath, searchPattern); - // Create a cancellation token source to cancel - // if the operation takes more than a minute. - using CancellationTokenSource cancellationTokenSource = - new CancellationTokenSource(1000*60); - - #region HIGHLIGHT - await foreach ((string fileName, string encryptedFileName) - in EncryptFilesAsync(files, cryptographer) - .Zip(files.ToAsyncEnumerable()) - .WithCancellation(cancellationTokenSource.Token) - ) - #endregion HIGHLIGHT - { - Console.WriteLine($"{fileName}=>{encryptedFileName}"); - } - } + // Create a cancellation token source to cancel + // if the operation takes more than a minute. + using CancellationTokenSource cancellationTokenSource = + new CancellationTokenSource(1000*60); #region HIGHLIGHT - public static async IAsyncEnumerable EncryptFilesAsync( - IEnumerable files, Cryptographer cryptographer, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + await foreach ((string fileName, string encryptedFileName) + in EncryptFilesAsync(files, cryptographer) + .Zip(files.ToAsyncEnumerable()) + .WithCancellation(cancellationTokenSource.Token) + ) #endregion HIGHLIGHT { - foreach (string fileName in files) - { - #region HIGHLIGHT - yield return await EncryptFileAsync(fileName, cryptographer); - #endregion HIGHLIGHT - cancellationToken.ThrowIfCancellationRequested(); - } + Console.WriteLine($"{fileName}=>{encryptedFileName}"); } + } - #region HIGHLIGHT - private static async ValueTask EncryptFileAsync( - string fileName, Cryptographer cryptographer) - #endregion HIGHLIGHT + #region HIGHLIGHT + public static async IAsyncEnumerable EncryptFilesAsync( + IEnumerable files, Cryptographer cryptographer, + [EnumeratorCancellation] CancellationToken cancellationToken = default) + #endregion HIGHLIGHT + { + foreach (string fileName in files) { - string encryptedFileName = $"{fileName}.encrypt"; #region HIGHLIGHT - await using FileStream outputFileStream = - new FileStream(encryptedFileName, FileMode.Create); + yield return await EncryptFileAsync(fileName, cryptographer); #endregion HIGHLIGHT + cancellationToken.ThrowIfCancellationRequested(); + } + } - #region HIGHLIGHT - string data = await File.ReadAllTextAsync(fileName); - - await cryptographer.EncryptAsync(data, outputFileStream); - #endregion HIGHLIGHT + #region HIGHLIGHT + private static async ValueTask EncryptFileAsync( + string fileName, Cryptographer cryptographer) + #endregion HIGHLIGHT + { + string encryptedFileName = $"{fileName}.encrypt"; + #region HIGHLIGHT + await using FileStream outputFileStream = + new FileStream(encryptedFileName, FileMode.Create); + #endregion HIGHLIGHT - return encryptedFileName; - } - #region EXCLUDE + #region HIGHLIGHT + string data = await File.ReadAllTextAsync(fileName); - // Included to simplify testing - public static Cryptographer? Cryptographer { get; private set; } + await cryptographer.EncryptAsync(data, outputFileStream); + #endregion HIGHLIGHT - private static void DisplayHelp() { /* ... */ } - #endregion EXCLUDE + return encryptedFileName; } - #endregion INCLUDE + #region EXCLUDE + + // Included to simplify testing + public static Cryptographer? Cryptographer { get; private set; } + + private static void DisplayHelp() { /* ... */ } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.07.AsynchronousStreamsInvocationWithAwaitForeach.cs b/src/Chapter20/Listing20.07.AsynchronousStreamsInvocationWithAwaitForeach.cs index ed4534f49..4e2cc843f 100644 --- a/src/Chapter20/Listing20.07.AsynchronousStreamsInvocationWithAwaitForeach.cs +++ b/src/Chapter20/Listing20.07.AsynchronousStreamsInvocationWithAwaitForeach.cs @@ -1,32 +1,31 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_07; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#region INCLUDE +public class AsyncEncryptionCollection : IAsyncEnumerable { - using System; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - #region INCLUDE - public class AsyncEncryptionCollection : IAsyncEnumerable + public async IAsyncEnumerator GetAsyncEnumerator( + CancellationToken cancellationToken = default) { - public async IAsyncEnumerator GetAsyncEnumerator( - CancellationToken cancellationToken = default) - { - #region EXCLUDE - // Mock code - yield return await Task.Run(() => (string)""); - #endregion EXCLUDE - } + #region EXCLUDE + // Mock code + yield return await Task.Run(() => (string)""); + #endregion EXCLUDE + } - public static async Task Main() - { - AsyncEncryptionCollection collection = - new AsyncEncryptionCollection(); - // ... + public static async Task Main() + { + AsyncEncryptionCollection collection = + new AsyncEncryptionCollection(); + // ... - await foreach (string fileName in collection) - { - Console.WriteLine(fileName); - } + await foreach (string fileName in collection) + { + Console.WriteLine(fileName); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.09.CatchingExceptionFromAsyncVoidMethod.cs b/src/Chapter20/Listing20.09.CatchingExceptionFromAsyncVoidMethod.cs index 2e11df99e..1ca137915 100644 --- a/src/Chapter20/Listing20.09.CatchingExceptionFromAsyncVoidMethod.cs +++ b/src/Chapter20/Listing20.09.CatchingExceptionFromAsyncVoidMethod.cs @@ -1,106 +1,105 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_09 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_09; + +#region INCLUDE +using System; +using System.Threading; +using System.Threading.Tasks; + +public class AsyncSynchronizationContext : SynchronizationContext { - #region INCLUDE - using System; - using System.Threading; - using System.Threading.Tasks; + public Exception? Exception { get; set; } + public ManualResetEventSlim ResetEvent { get; } = + new ManualResetEventSlim(); - public class AsyncSynchronizationContext : SynchronizationContext + public override void Send(SendOrPostCallback callback, object? state) { - public Exception? Exception { get; set; } - public ManualResetEventSlim ResetEvent { get; } = - new ManualResetEventSlim(); - - public override void Send(SendOrPostCallback callback, object? state) + try { - try - { - Console.WriteLine($@"Send notification invoked...(Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - callback(state); - } - catch (Exception exception) - { - Exception = exception; - } - finally - { - ResetEvent.Set(); - } + Console.WriteLine($@"Send notification invoked...(Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + callback(state); } - - public override void Post(SendOrPostCallback callback, object? state) + catch (Exception exception) { - try - { - Console.WriteLine($@"Post notification invoked...(Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - callback(state); - } - catch (Exception exception) - { - Exception = exception; - } - finally - { - ResetEvent.Set(); - } + Exception = exception; + } + finally + { + ResetEvent.Set(); } } - public static class Program + public override void Post(SendOrPostCallback callback, object? state) { - public static bool EventTriggered { get; set; } + try + { + Console.WriteLine($@"Post notification invoked...(Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + callback(state); + } + catch (Exception exception) + { + Exception = exception; + } + finally + { + ResetEvent.Set(); + } + } +} - public const string ExpectedExceptionMessage = "Expected Exception"; +public static class Program +{ + public static bool EventTriggered { get; set; } + + public const string ExpectedExceptionMessage = "Expected Exception"; - public static void Main() + public static void Main() + { + SynchronizationContext? originalSynchronizationContext = + SynchronizationContext.Current; + try { - SynchronizationContext? originalSynchronizationContext = - SynchronizationContext.Current; - try - { - AsyncSynchronizationContext synchronizationContext = - new AsyncSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext( - synchronizationContext); + AsyncSynchronizationContext synchronizationContext = + new AsyncSynchronizationContext(); + SynchronizationContext.SetSynchronizationContext( + synchronizationContext); - OnEvent(typeof(Program), EventArgs.Empty); + OnEvent(typeof(Program), EventArgs.Empty); - synchronizationContext.ResetEvent.Wait(); + synchronizationContext.ResetEvent.Wait(); - if (synchronizationContext.Exception != null) - { - Console.WriteLine($@"Throwing expected exception....(Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture( - synchronizationContext.Exception).Throw(); - } - } - catch (Exception exception) + if (synchronizationContext.Exception != null) { - Console.WriteLine($@"{exception} thrown as expected.(Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - } - finally - { - SynchronizationContext.SetSynchronizationContext( - originalSynchronizationContext); + Console.WriteLine($@"Throwing expected exception....(Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture( + synchronizationContext.Exception).Throw(); } } - - private static async void OnEvent(object sender, EventArgs eventArgs) + catch (Exception exception) { - Console.WriteLine($@"Invoking Task.Run...(Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - await Task.Run(() => - { - EventTriggered = true; - Console.WriteLine($@"Running task... (Thread ID: { - Thread.CurrentThread.ManagedThreadId})"); - throw new Exception(ExpectedExceptionMessage); - }); + Console.WriteLine($@"{exception} thrown as expected.(Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + } + finally + { + SynchronizationContext.SetSynchronizationContext( + originalSynchronizationContext); } } - #endregion INCLUDE + + private static async void OnEvent(object sender, EventArgs eventArgs) + { + Console.WriteLine($@"Invoking Task.Run...(Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + await Task.Run(() => + { + EventTriggered = true; + Console.WriteLine($@"Running task... (Thread ID: { + Thread.CurrentThread.ManagedThreadId})"); + throw new Exception(ExpectedExceptionMessage); + }); + } } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.10.AsynchronousAsALambda.cs b/src/Chapter20/Listing20.10.AsynchronousAsALambda.cs index 015390981..05ff8df92 100644 --- a/src/Chapter20/Listing20.10.AsynchronousAsALambda.cs +++ b/src/Chapter20/Listing20.10.AsynchronousAsALambda.cs @@ -1,83 +1,82 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_10 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_10; + +#region INCLUDE +using System; +using System.IO; +using System.Net; +using System.Linq; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.IO; - using System.Net; - using System.Linq; - using System.Threading.Tasks; - public class Program + public static void Main(string[] args) { - - public static void Main(string[] args) + string url = "http://www.IntelliTect.com"; + if(args.Length > 0) { - string url = "http://www.IntelliTect.com"; - if(args.Length > 0) - { - url = args[0]; - } + url = args[0]; + } - Console.Write(url); + Console.Write(url); - Func writeWebRequestSizeAsync = - #region HIGHLIGHT - async (string webRequestUrl) => + Func writeWebRequestSizeAsync = + #region HIGHLIGHT + async (string webRequestUrl) => + #endregion HIGHLIGHT + { + // Error handling omitted for + // elucidation + WebRequest webRequest = + WebRequest.Create(url); + + WebResponse response = + #region HIGHLIGHT + await webRequest.GetResponseAsync(); #endregion HIGHLIGHT - { - // Error handling omitted for - // elucidation - WebRequest webRequest = - WebRequest.Create(url); - WebResponse response = + // Explicitly counting rather than invoking + // webRequest.ContentLength to demonstrate + // multiple await operators + using (StreamReader reader = + new StreamReader( + response.GetResponseStream())) + { + string text = #region HIGHLIGHT - await webRequest.GetResponseAsync(); + (await reader.ReadToEndAsync()); #endregion HIGHLIGHT + Console.WriteLine( + FormatBytes(text.Length)); + } + }; - // Explicitly counting rather than invoking - // webRequest.ContentLength to demonstrate - // multiple await operators - using (StreamReader reader = - new StreamReader( - response.GetResponseStream())) - { - string text = - #region HIGHLIGHT - (await reader.ReadToEndAsync()); - #endregion HIGHLIGHT - Console.WriteLine( - FormatBytes(text.Length)); - } - }; - - #region HIGHLIGHT - Task task = writeWebRequestSizeAsync(url); - #endregion HIGHLIGHT + #region HIGHLIGHT + Task task = writeWebRequestSizeAsync(url); + #endregion HIGHLIGHT - while (!task.Wait(100)) - { - Console.Write("."); - } - } - #region EXCLUDE - static public string FormatBytes(long bytes) + while (!task.Wait(100)) { - string[] magnitudes = - new string[] { "GB", "MB", "KB", "Bytes" }; - long max = - (long)Math.Pow(1024, magnitudes.Length); - - return string.Format("{1:##.##} {0}", - magnitudes.FirstOrDefault( - magnitude => - bytes > (max /= 1024)) ?? "0 Bytes", - (decimal)bytes / (decimal)max).Trim(); + Console.Write("."); } - #endregion EXCLUDE } - #endregion INCLUDE + #region EXCLUDE + static public string FormatBytes(long bytes) + { + string[] magnitudes = + new string[] { "GB", "MB", "KB", "Bytes" }; + long max = + (long)Math.Pow(1024, magnitudes.Length); + + return string.Format("{1:##.##} {0}", + magnitudes.FirstOrDefault( + magnitude => + bytes > (max /= 1024)) ?? "0 Bytes", + (decimal)bytes / (decimal)max).Trim(); + } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.11.ImplementingCustomAsynchronousMethod.cs b/src/Chapter20/Listing20.11.ImplementingCustomAsynchronousMethod.cs index 7ddeecce1..f875b43b1 100644 --- a/src/Chapter20/Listing20.11.ImplementingCustomAsynchronousMethod.cs +++ b/src/Chapter20/Listing20.11.ImplementingCustomAsynchronousMethod.cs @@ -1,55 +1,54 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_11 -{ - #region INCLUDE - using System.Diagnostics; - using System.Threading; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_11; + +#region INCLUDE +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; - public class Program +public class Program +{ + public static Task RunProcessAsync( + string fileName, + string arguments = "", + CancellationToken cancellationToken = default) { - public static Task RunProcessAsync( - string fileName, - string arguments = "", - CancellationToken cancellationToken = default) - { - TaskCompletionSource taskCS = - new TaskCompletionSource(); + TaskCompletionSource taskCS = + new TaskCompletionSource(); - Process process = new Process() - { - StartInfo = new ProcessStartInfo(fileName) - { - UseShellExecute = false, - Arguments = arguments - }, - EnableRaisingEvents = true - }; - - process.Exited += (sender, localEventArgs) => + Process process = new Process() + { + StartInfo = new ProcessStartInfo(fileName) { - taskCS.SetResult(process); - }; + UseShellExecute = false, + Arguments = arguments + }, + EnableRaisingEvents = true + }; - #region HIGHLIGHT - cancellationToken - .ThrowIfCancellationRequested(); - #endregion HIGHLIGHT + process.Exited += (sender, localEventArgs) => + { + taskCS.SetResult(process); + }; - process.Start(); + #region HIGHLIGHT + cancellationToken + .ThrowIfCancellationRequested(); + #endregion HIGHLIGHT - #region HIGHLIGHT - cancellationToken.Register(() => - { - Process.GetProcessById(process.Id).Kill(); - }); - #endregion HIGHLIGHT + process.Start(); + + #region HIGHLIGHT + cancellationToken.Register(() => + { + Process.GetProcessById(process.Id).Kill(); + }); + #endregion HIGHLIGHT - return taskCS.Task; - } - // ... + return taskCS.Task; } - #endregion INCLUDE + // ... } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.12.CustomMethodWithProgressSupport.cs b/src/Chapter20/Listing20.12.CustomMethodWithProgressSupport.cs index a07538132..8d2370e31 100644 --- a/src/Chapter20/Listing20.12.CustomMethodWithProgressSupport.cs +++ b/src/Chapter20/Listing20.12.CustomMethodWithProgressSupport.cs @@ -1,87 +1,86 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_12 -{ - #region INCLUDE - using System; - using System.Diagnostics; - using System.Threading; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_12; + +#region INCLUDE +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; - public class Program +public class Program +{ + public static Task RunProcessAsync( + string fileName, + string arguments = "", + #region HIGHLIGHT + IProgress? progress = + null, object? objectState = null, + #endregion HIGHLIGHT + CancellationToken cancellationToken = + default(CancellationToken)) { - public static Task RunProcessAsync( - string fileName, - string arguments = "", - #region HIGHLIGHT - IProgress? progress = - null, object? objectState = null, - #endregion HIGHLIGHT - CancellationToken cancellationToken = - default(CancellationToken)) - { - TaskCompletionSource taskCS = - new TaskCompletionSource(); + TaskCompletionSource taskCS = + new TaskCompletionSource(); - Process process = new Process() + Process process = new Process() + { + StartInfo = new ProcessStartInfo(fileName) { - StartInfo = new ProcessStartInfo(fileName) - { - UseShellExecute = false, - Arguments = arguments, - #region HIGHLIGHT - RedirectStandardOutput = - progress != null - #endregion HIGHLIGHT - }, - EnableRaisingEvents = true - }; + UseShellExecute = false, + Arguments = arguments, + #region HIGHLIGHT + RedirectStandardOutput = + progress != null + #endregion HIGHLIGHT + }, + EnableRaisingEvents = true + }; - process.Exited += (sender, localEventArgs) => - { - taskCS.SetResult(process); - }; + process.Exited += (sender, localEventArgs) => + { + taskCS.SetResult(process); + }; - #region HIGHLIGHT - if (progress != null) + #region HIGHLIGHT + if (progress != null) + { + process.OutputDataReceived += + (sender, localEventArgs) => { - process.OutputDataReceived += - (sender, localEventArgs) => - { - progress.Report( - new ProcessProgressEventArgs( - localEventArgs.Data, - objectState)); - }; - } - #endregion HIGHLIGHT - - cancellationToken - .ThrowIfCancellationRequested(); - - process.Start(); + progress.Report( + new ProcessProgressEventArgs( + localEventArgs.Data, + objectState)); + }; + } + #endregion HIGHLIGHT - #region HIGHLIGHT - if (progress !=null) - { - process.BeginOutputReadLine(); - } - #endregion HIGHLIGHT + cancellationToken + .ThrowIfCancellationRequested(); - cancellationToken.Register(() => - { - Process.GetProcessById(process.Id).Kill(); - }); + process.Start(); - return taskCS.Task; + #region HIGHLIGHT + if (progress !=null) + { + process.BeginOutputReadLine(); } + #endregion HIGHLIGHT - // ... - } + cancellationToken.Register(() => + { + Process.GetProcessById(process.Id).Kill(); + }); - public class ProcessProgressEventArgs - { - #region EXCLUDE - public ProcessProgressEventArgs(string? _,object? __){} - #endregion EXCLUDE + return taskCS.Task; } - #endregion INCLUDE + + // ... +} + +public class ProcessProgressEventArgs +{ + #region EXCLUDE + public ProcessProgressEventArgs(string? _,object? __){} + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter20/Listing20.13.CallingTaskContinueWith.cs b/src/Chapter20/Listing20.13.CallingTaskContinueWith.cs index cc9e3000b..c590d5644 100644 --- a/src/Chapter20/Listing20.13.CallingTaskContinueWith.cs +++ b/src/Chapter20/Listing20.13.CallingTaskContinueWith.cs @@ -1,40 +1,39 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter20.Listing20_13; + +#region INCLUDE +using System; +using System.Threading; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.Threading; - using System.Threading.Tasks; + public static void Main() + { + DisplayStatus("Before"); + Task taskA = + Task.Run(() => + DisplayStatus("Starting...")) + .ContinueWith(antecedent => + DisplayStatus("Continuing A...")); + Task taskB = taskA.ContinueWith(antecedent => + DisplayStatus("Continuing B...")); + Task taskC = taskA.ContinueWith(antecedent => + DisplayStatus("Continuing C...")); + Task.WaitAll(taskB, taskC); + DisplayStatus("Finished!"); + } - public class Program + private static void DisplayStatus(string message) { - public static void Main() - { - DisplayStatus("Before"); - Task taskA = - Task.Run(() => - DisplayStatus("Starting...")) - .ContinueWith(antecedent => - DisplayStatus("Continuing A...")); - Task taskB = taskA.ContinueWith(antecedent => - DisplayStatus("Continuing B...")); - Task taskC = taskA.ContinueWith(antecedent => - DisplayStatus("Continuing C...")); - Task.WaitAll(taskB, taskC); - DisplayStatus("Finished!"); - } - - private static void DisplayStatus(string message) - { - string text = - $@"{ Thread.CurrentThread.ManagedThreadId - }: { message }"; - - - Console.WriteLine(text); - } + string text = + $@"{ Thread.CurrentThread.ManagedThreadId + }: { message }"; + + + Console.WriteLine(text); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter21/Listing21.01.SynchronousPiSections.cs b/src/Chapter21/Listing21.01.SynchronousPiSections.cs index 660e00e3e..05afc6cf2 100644 --- a/src/Chapter21/Listing21.01.SynchronousPiSections.cs +++ b/src/Chapter21/Listing21.01.SynchronousPiSections.cs @@ -1,47 +1,46 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_01; + +#region INCLUDE +using System; +using AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public class Program { - #region INCLUDE - using System; - using AddisonWesley.Michaelis.EssentialCSharp.Shared; + const int TotalDigits = 100; + const int BatchSize = 10; - public class Program + public static void Main() { - const int TotalDigits = 100; - const int BatchSize = 10; - - public static void Main() + string pi = ""; + const int iterations = TotalDigits / BatchSize; + for(int i = 0; i < iterations; i++) { - string pi = ""; - const int iterations = TotalDigits / BatchSize; - for(int i = 0; i < iterations; i++) - { - pi += PiCalculator.Calculate( - BatchSize, i * BatchSize); - } - - Console.WriteLine(pi); + pi += PiCalculator.Calculate( + BatchSize, i * BatchSize); } + + Console.WriteLine(pi); } - #region EXCLUDE - /* - #endregion EXCLUDE - using System; +} +#region EXCLUDE +/* +#endregion EXCLUDE +using System; - public static class PiCalculator +public static class PiCalculator +{ + public static string Calculate( + int digits, int startingAt) { - public static string Calculate( - int digits, int startingAt) - { - //... - } - //... } - #region EXCLUDE - */ - #endregion EXCLUDE - #endregion INCLUDE + + //... } +#region EXCLUDE +*/ +#endregion EXCLUDE +#endregion INCLUDE diff --git a/src/Chapter21/Listing21.02.ParallelPiCalculation.cs b/src/Chapter21/Listing21.02.ParallelPiCalculation.cs index 6b338dff6..a11f46793 100644 --- a/src/Chapter21/Listing21.02.ParallelPiCalculation.cs +++ b/src/Chapter21/Listing21.02.ParallelPiCalculation.cs @@ -1,38 +1,37 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_02 -{ - #region INCLUDE - using System; - #region HIGHLIGHT - using System.Threading.Tasks; - #endregion HIGHLIGHT - using AddisonWesley.Michaelis.EssentialCSharp.Shared; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_02; - //... +#region INCLUDE +using System; +#region HIGHLIGHT +using System.Threading.Tasks; +#endregion HIGHLIGHT +using AddisonWesley.Michaelis.EssentialCSharp.Shared; - public class Program - { - const int TotalDigits = 100; - const int BatchSize = 10; +//... + +public class Program +{ + const int TotalDigits = 100; + const int BatchSize = 10; - public static void Main() + public static void Main() + { + string pi = ""; + const int iterations = TotalDigits / BatchSize; + string[] sections = new string[iterations]; + #region HIGHLIGHT + Parallel.For(0, iterations, i => { - string pi = ""; - const int iterations = TotalDigits / BatchSize; - string[] sections = new string[iterations]; - #region HIGHLIGHT - Parallel.For(0, iterations, i => - { - sections[i] = PiCalculator.Calculate( - BatchSize, i * BatchSize); - }); - #endregion HIGHLIGHT - - pi = string.Join("", sections); - Console.WriteLine(pi); - } + sections[i] = PiCalculator.Calculate( + BatchSize, i * BatchSize); + }); + #endregion HIGHLIGHT + + pi = string.Join("", sections); + Console.WriteLine(pi); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter21/Listing21.03.ParallelForeachLoop.cs b/src/Chapter21/Listing21.03.ParallelForeachLoop.cs index eec9647f2..bfa973606 100644 --- a/src/Chapter21/Listing21.03.ParallelForeachLoop.cs +++ b/src/Chapter21/Listing21.03.ParallelForeachLoop.cs @@ -1,75 +1,70 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_03 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Shared; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.IO; - #region HIGHLIGHT - using System.Threading.Tasks; - #endregion HIGHLIGHT +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_03; + +using AddisonWesley.Michaelis.EssentialCSharp.Shared; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.IO; +#region HIGHLIGHT +using System.Threading.Tasks; +#endregion HIGHLIGHT - public class Program +public class Program +{ + #region EXCLUDE + public static void Main() { - #region EXCLUDE - public static void Main() - { - EncryptFiles(Directory.GetCurrentDirectory(), "*.*"); - } - #endregion EXCLUDE - public static void EncryptFiles( - string directoryPath, string searchPattern) + EncryptFiles(Directory.GetCurrentDirectory(), "*.*"); + } + #endregion EXCLUDE + public static void EncryptFiles( + string directoryPath, string searchPattern) - { - IEnumerable files = Directory.EnumerateFiles( - directoryPath, searchPattern, - SearchOption.AllDirectories); + { + IEnumerable files = Directory.EnumerateFiles( + directoryPath, searchPattern, + SearchOption.AllDirectories); - #region HIGHLIGHT - Parallel.ForEach(files, fileName => - { - Encrypt(fileName); - }); - #endregion HIGHLIGHT - } - #region EXCLUDE - public static string Encrypt(string fileName) + #region HIGHLIGHT + Parallel.ForEach(files, fileName => { - string outputFileName = $"{fileName}.encrypt"; - Encrypt(fileName, outputFileName); - return outputFileName; - } + Encrypt(fileName); + }); + #endregion HIGHLIGHT + } + #region EXCLUDE + public static string Encrypt(string fileName) + { + string outputFileName = $"{fileName}.encrypt"; + Encrypt(fileName, outputFileName); + return outputFileName; + } - static Cryptographer Cryptographer { get; } = new Cryptographer(); + static Cryptographer Cryptographer { get; } = new Cryptographer(); - public static void Encrypt(string inputFileName, string outputFileName) + public static void Encrypt(string inputFileName, string outputFileName) + { + Console.WriteLine($">>>>>Encrypting '{ inputFileName }'."); + using (FileStream outputFileStream = new FileStream($"{inputFileName}.encrypt", FileMode.Create)) { - Console.WriteLine($">>>>>Encrypting '{ inputFileName }'."); - using (FileStream outputFileStream = new FileStream($"{inputFileName}.encrypt", FileMode.Create)) - { - byte[] encryptedText = Cryptographer.EncryptAsync(File.ReadAllText(inputFileName), outputFileStream).Result; - } - Console.WriteLine($"<<<<>>>>Decrypting '{ inputFileName }'."); + byte[] bytes = File.ReadAllBytes(inputFileName); + using (FileStream outputFileStream = new FileStream(outputFileName, FileMode.Create)) { - Console.WriteLine($">>>>>Decrypting '{ inputFileName }'."); - byte[] bytes = File.ReadAllBytes(inputFileName); - using (FileStream outputFileStream = new FileStream(outputFileName, FileMode.Create)) - { - Cryptographer.DecryptAsync(bytes, outputFileStream).Wait(); - } - Console.WriteLine($"<<<< files = Directory.EnumerateFiles( + directoryPath, searchPattern, + SearchOption.AllDirectories); + try { - EncryptFiles(Directory.GetCurrentDirectory(), "*.*"); + Parallel.ForEach(files, fileName => + { + Encrypt(fileName); + }); } - #endregion EXCLUDE - static void EncryptFiles( - string directoryPath, string searchPattern) + #region HIGHLIGHT + catch (AggregateException exception) + #endregion HIGHLIGHT { - IEnumerable files = Directory.EnumerateFiles( - directoryPath, searchPattern, - SearchOption.AllDirectories); - try - { - Parallel.ForEach(files, fileName => - { - Encrypt(fileName); - }); - } + Console.WriteLine( + "ERROR: {0}:", + exception.GetType().Name); + foreach(Exception item in #region HIGHLIGHT - catch (AggregateException exception) + exception.InnerExceptions) #endregion HIGHLIGHT { - Console.WriteLine( - "ERROR: {0}:", - exception.GetType().Name); - foreach(Exception item in - #region HIGHLIGHT - exception.InnerExceptions) - #endregion HIGHLIGHT - { - Console.WriteLine(" {0} - {1}", - item.GetType().Name, item.Message); - } + Console.WriteLine(" {0} - {1}", + item.GetType().Name, item.Message); } } - #region EXCLUDE - private static void Encrypt(string fileName) - { - // ... - - throw new UnauthorizedAccessException(); - } - #endregion EXCLUDE } - #endregion INCLUDE + #region EXCLUDE + private static void Encrypt(string fileName) + { + // ... + throw new UnauthorizedAccessException(); + } + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter21/Listing21.05.CancelingParallelLoop.cs b/src/Chapter21/Listing21.05.CancelingParallelLoop.cs index c8a864dd0..028fb85ae 100644 --- a/src/Chapter21/Listing21.05.CancelingParallelLoop.cs +++ b/src/Chapter21/Listing21.05.CancelingParallelLoop.cs @@ -1,85 +1,84 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_05 -{ - using AddisonWesley.Michaelis.EssentialCSharp.Shared; - #region INCLUDE - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter21.Listing21_05; + +using AddisonWesley.Michaelis.EssentialCSharp.Shared; +#region INCLUDE +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; - public class Program +public class Program +{ + #region EXCLUDE + public static void Main() { - #region EXCLUDE - public static void Main() - { - EncryptFiles($@"{Directory.GetCurrentDirectory()}\..\..\", "*.*"); - } - #endregion EXCLUDE + EncryptFiles($@"{Directory.GetCurrentDirectory()}\..\..\", "*.*"); + } + #endregion EXCLUDE - static void EncryptFiles( - string directoryPath, string searchPattern) - { + static void EncryptFiles( + string directoryPath, string searchPattern) + { - string stars = - "*".PadRight(Console.WindowWidth - 1, '*'); + string stars = + "*".PadRight(Console.WindowWidth - 1, '*'); - IEnumerable files = Directory.GetFiles( - directoryPath, searchPattern, - SearchOption.AllDirectories); + IEnumerable files = Directory.GetFiles( + directoryPath, searchPattern, + SearchOption.AllDirectories); - #region HIGHLIGHT - CancellationTokenSource cts = - new CancellationTokenSource(); - ParallelOptions parallelOptions = - new ParallelOptions { CancellationToken = cts.Token }; - cts.Token.Register( - () => Console.WriteLine("Canceling...")); - #endregion HIGHLIGHT + #region HIGHLIGHT + CancellationTokenSource cts = + new CancellationTokenSource(); + ParallelOptions parallelOptions = + new ParallelOptions { CancellationToken = cts.Token }; + cts.Token.Register( + () => Console.WriteLine("Canceling...")); + #endregion HIGHLIGHT - Console.WriteLine("Press ENTER to exit."); + Console.WriteLine("Press ENTER to exit."); - Task task = Task.Run(() => + Task task = Task.Run(() => + { + try { - try - { - Parallel.ForEach( - #region HIGHLIGHT - files, parallelOptions, - #endregion HIGHLIGHT - (fileName, loopState) => - { - Encrypt(fileName); - }); - } - catch(OperationCanceledException) { } - }); + Parallel.ForEach( + #region HIGHLIGHT + files, parallelOptions, + #endregion HIGHLIGHT + (fileName, loopState) => + { + Encrypt(fileName); + }); + } + catch(OperationCanceledException) { } + }); - // Wait for the user's input - Console.ReadLine(); + // Wait for the user's input + Console.ReadLine(); - // Cancel the query - #region HIGHLIGHT - cts.Cancel(); - #endregion HIGHLIGHT - Console.Write(stars); - task.Wait(); - } - #region EXCLUDE + // Cancel the query + #region HIGHLIGHT + cts.Cancel(); + #endregion HIGHLIGHT + Console.Write(stars); + task.Wait(); + } + #region EXCLUDE - private static void Encrypt(string fileName) - { - if (Path.GetExtension(fileName) == ".encrypt") return; - Console.WriteLine($">>>>>Encrypting '{ fileName }'."); - Cryptographer cryptographer = new Cryptographer(); - File.Delete($"{fileName}.encrypt"); - byte[] encryptedText = cryptographer.Encrypt(File.ReadAllText(fileName)); - File.WriteAllBytes($"{fileName}.encrypt", encryptedText); - Console.WriteLine($"<<<<>>>>Encrypting '{ fileName }'."); + Cryptographer cryptographer = new Cryptographer(); + File.Delete($"{fileName}.encrypt"); + byte[] encryptedText = cryptographer.Encrypt(File.ReadAllText(fileName)); + File.WriteAllBytes($"{fileName}.encrypt", encryptedText); + Console.WriteLine($"<<<< + Encrypt(IEnumerable data) + { + return data.Select( + item => Encrypt(item)).ToList(); + } + #region EXCLUDE + private static string Encrypt(string item) { - // ... - public static List - Encrypt(IEnumerable data) - { - return data.Select( - item => Encrypt(item)).ToList(); - } - #region EXCLUDE - private static string Encrypt(string item) - { - Console.WriteLine($">>>>>Encrypting '{ item }'."); - Cryptographer cryptographer = new Cryptographer(); - string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); - Console.WriteLine($"<<<<>>>>Encrypting '{ item }'."); + Cryptographer cryptographer = new Cryptographer(); + string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); + Console.WriteLine($"<<<< + Encrypt(IEnumerable data) + { + #region HIGHLIGHT + return data.AsParallel().Select( + #endregion HIGHLIGHT + item => Encrypt(item)).ToList(); + } + #region EXCLUDE + private static string Encrypt(string item) { - // ... - public static List - Encrypt(IEnumerable data) - { - #region HIGHLIGHT - return data.AsParallel().Select( - #endregion HIGHLIGHT - item => Encrypt(item)).ToList(); - } - #region EXCLUDE - private static string Encrypt(string item) - { - Console.WriteLine($">>>>>Encrypting '{ item }'."); - Cryptographer cryptographer = new Cryptographer(); - string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); - Console.WriteLine($"<<<<>>>>Encrypting '{ item }'."); + Cryptographer cryptographer = new Cryptographer(); + string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); + Console.WriteLine($"<<<< + Encrypt(IEnumerable data) { - // ... - public static List - Encrypt(IEnumerable data) + #region INCLUDE + //... + #region HIGHLIGHT + OrderedParallelQuery parallelGroups = + data.AsParallel().OrderBy(item => item); + #endregion HIGHLIGHT + + // Show the total count of items still + // matches the original count + if (data.Count() != parallelGroups.Sum( + item => item.Length)) { - #region INCLUDE - //... - #region HIGHLIGHT - OrderedParallelQuery parallelGroups = - data.AsParallel().OrderBy(item => item); - #endregion HIGHLIGHT - - // Show the total count of items still - // matches the original count - if (data.Count() != parallelGroups.Sum( - item => item.Length)) - { - throw new Exception("data.Count() != parallelGroups.Sum(item => item.Count()"); - } - // ... - #endregion INCLUDE - - return data.AsParallel().Select( - item => Program.Encrypt(item)).ToList(); + throw new Exception("data.Count() != parallelGroups.Sum(item => item.Count()"); } - // ... + #endregion INCLUDE - private static string Encrypt(string item) - { - Console.WriteLine($">>>>>Encrypting '{ item }'."); - Cryptographer cryptographer = new Cryptographer(); - string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); - Console.WriteLine($"<<<< Program.Encrypt(item)).ToList(); + } + + // ... + private static string Encrypt(string item) + { + Console.WriteLine($">>>>>Encrypting '{ item }'."); + Cryptographer cryptographer = new Cryptographer(); + string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); + Console.WriteLine($"<<<< + Encrypt(IEnumerable data) { - // ... - public static List - Encrypt(IEnumerable data) + #region INCLUDE + //... + ParallelQuery> parallelGroups; + parallelGroups = + #region HIGHLIGHT + from text in data.AsParallel() + orderby text + group text by text[0]; + #endregion HIGHLIGHT + + // Show the total count of items still + // matches the original count + if (data.Count() != parallelGroups.Sum( + item => item.Count())) { - #region INCLUDE - //... - ParallelQuery> parallelGroups; - parallelGroups = - #region HIGHLIGHT - from text in data.AsParallel() - orderby text - group text by text[0]; - #endregion HIGHLIGHT - - // Show the total count of items still - // matches the original count - if (data.Count() != parallelGroups.Sum( - item => item.Count())) - { - throw new Exception("data.Count() != parallelGroups.Sum(item => item.Count()"); - } - //... - #endregion INCLUDE - - return data.AsParallel().Select( - item => Encrypt(item)).ToList(); + throw new Exception("data.Count() != parallelGroups.Sum(item => item.Count()"); } + //... + #endregion INCLUDE - // ... + return data.AsParallel().Select( + item => Encrypt(item)).ToList(); + } - private static string Encrypt(string item) - { - Console.WriteLine($">>>>>Encrypting '{ item }'."); - Cryptographer cryptographer = new Cryptographer(); - string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); - Console.WriteLine($"<<<<>>>>Encrypting '{ item }'."); + Cryptographer cryptographer = new Cryptographer(); + string itemEncrypted = System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); + Console.WriteLine($"<<<< ParallelEncrypt( + List data, + CancellationToken cancellationToken) { - public static List ParallelEncrypt( - List data, - CancellationToken cancellationToken) - { - int govener = 0; - return data.AsParallel().WithCancellation( - cancellationToken).Select( - (item) => + int govener = 0; + return data.AsParallel().WithCancellation( + cancellationToken).Select( + (item) => + { + if (Interlocked.CompareExchange( + ref govener, 0, 100) % 100 == 0) { - if (Interlocked.CompareExchange( - ref govener, 0, 100) % 100 == 0) - { - Console.Write('.'); - } - Interlocked.Increment(ref govener); - return Encrypt(item); - }).ToList(); - } + Console.Write('.'); + } + Interlocked.Increment(ref govener); + return Encrypt(item); + }).ToList(); + } - public static async Task Main() - { - ConsoleColor originalColor = Console.ForegroundColor; - List data = Utility.GetData(100000).ToList(); + public static async Task Main() + { + ConsoleColor originalColor = Console.ForegroundColor; + List data = Utility.GetData(100000).ToList(); - using CancellationTokenSource cts = - new CancellationTokenSource(); + using CancellationTokenSource cts = + new CancellationTokenSource(); - Task task = Task.Run(() => - { - data = ParallelEncrypt(data, cts.Token); - }, cts.Token); + Task task = Task.Run(() => + { + data = ParallelEncrypt(data, cts.Token); + }, cts.Token); - Console.WriteLine("Press any key to Exit."); - Task cancelTask = ConsoleReadAsync(cts.Token); + Console.WriteLine("Press any key to Exit."); + Task cancelTask = ConsoleReadAsync(cts.Token); - try - { - Task.WaitAny(task, cancelTask); - // Cancel whichever task has not finished. - cts.Cancel(); - await task; + try + { + Task.WaitAny(task, cancelTask); + // Cancel whichever task has not finished. + cts.Cancel(); + await task; - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("\nCompleted successfully"); + Console.ForegroundColor = ConsoleColor.Green; + Console.WriteLine("\nCompleted successfully"); - } - catch (OperationCanceledException taskCanceledException) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine( - $"\nCancelled: { taskCanceledException.Message }"); - } - finally - { - Console.ForegroundColor = originalColor; - } } + catch (OperationCanceledException taskCanceledException) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine( + $"\nCancelled: { taskCanceledException.Message }"); + } + finally + { + Console.ForegroundColor = originalColor; + } + } - private static async Task ConsoleReadAsync( - CancellationToken cancellationToken = default) + private static async Task ConsoleReadAsync( + CancellationToken cancellationToken = default) + { + return await Task.Run(async () => { - return await Task.Run(async () => + const int maxDelay = 1025; + int delay = 0; + while (!cancellationToken.IsCancellationRequested) { - const int maxDelay = 1025; - int delay = 0; - while (!cancellationToken.IsCancellationRequested) + if (Console.KeyAvailable) { - if (Console.KeyAvailable) - { - return Console.Read(); - } - else - { - await Task.Delay(delay, cancellationToken); - if (delay < maxDelay) delay *= 2 + 1; - } + return Console.Read(); } - cancellationToken.ThrowIfCancellationRequested(); - throw new InvalidOperationException( - "Previous line should throw preventing this from ever executing"); - }, cancellationToken); - } + else + { + await Task.Delay(delay, cancellationToken); + if (delay < maxDelay) delay *= 2 + 1; + } + } + cancellationToken.ThrowIfCancellationRequested(); + throw new InvalidOperationException( + "Previous line should throw preventing this from ever executing"); + }, cancellationToken); + } - private static string Encrypt(string item) - { - Cryptographer cryptographer = new Cryptographer(); - return System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); - } + private static string Encrypt(string item) + { + Cryptographer cryptographer = new Cryptographer(); + return System.Text.Encoding.UTF8.GetString(cryptographer.Encrypt(item)); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter21/Utility.cs b/src/Chapter21/Utility.cs index e221105ab..f4dc9b439 100644 --- a/src/Chapter21/Utility.cs +++ b/src/Chapter21/Utility.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared -{ - using System; - using System.Collections.Generic; +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +using System; +using System.Collections.Generic; - static class Utility +static class Utility +{ + public static IEnumerable GetData(int count) { - public static IEnumerable GetData(int count) - { - for(int i = 0; i < count; i++) - yield return Guid.NewGuid().ToString(); - } + for(int i = 0; i < count; i++) + yield return Guid.NewGuid().ToString(); } } diff --git a/src/Chapter22/Listing22.01.UnsychronizedState.cs b/src/Chapter22/Listing22.01.UnsychronizedState.cs index 416497b20..8387967f9 100644 --- a/src/Chapter22/Listing22.01.UnsychronizedState.cs +++ b/src/Chapter22/Listing22.01.UnsychronizedState.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_01; + +#region INCLUDE +using System; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.Threading.Tasks; + static int _Total = int.MaxValue; + static int _Count = 0; - public class Program + public static int Main(string[] args) { - static int _Total = int.MaxValue; - static int _Count = 0; + if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } - public static int Main(string[] args) - { - if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } + Console.WriteLine($"Increment and decrementing {_Total} times..."); - Console.WriteLine($"Increment and decrementing {_Total} times..."); + // Use Task.Factory.StartNew for .NET 4.0 + Task task = Task.Run(() => Decrement()); - // Use Task.Factory.StartNew for .NET 4.0 - Task task = Task.Run(() => Decrement()); - - // Increment - for(int i = 0; i < _Total; i++) - { - _Count++; - } + // Increment + for(int i = 0; i < _Total; i++) + { + _Count++; + } - task.Wait(); - Console.WriteLine($"Count = {_Count}"); + task.Wait(); + Console.WriteLine($"Count = {_Count}"); - return _Count; - } + return _Count; + } - public static void Decrement() + public static void Decrement() + { + // Decrement + for(int i = 0; i < _Total; i++) { - // Decrement - for(int i = 0; i < _Total; i++) - { - _Count--; - } + _Count--; } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.02.UnsychronizedLocalVariables.cs b/src/Chapter22/Listing22.02.UnsychronizedLocalVariables.cs index c21893b23..c68feb30f 100644 --- a/src/Chapter22/Listing22.02.UnsychronizedLocalVariables.cs +++ b/src/Chapter22/Listing22.02.UnsychronizedLocalVariables.cs @@ -1,25 +1,24 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_02 -{ - #region INCLUDE - using System; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_02; + +#region INCLUDE +using System; +using System.Threading.Tasks; - public class Program +public class Program +{ + public static int Main(string[] args) { - public static int Main(string[] args) + int total = int.MaxValue; + if (args?.Length > 0) { _ = int.TryParse(args[0], out total); } + Console.WriteLine($"Increment and decrementing {total} times..."); + int x = 0; + Parallel.For(0, total, i => { - int total = int.MaxValue; - if (args?.Length > 0) { _ = int.TryParse(args[0], out total); } - Console.WriteLine($"Increment and decrementing {total} times..."); - int x = 0; - Parallel.For(0, total, i => - { - x++; - x--; - }); - Console.WriteLine($"Count = {x}"); - return x; - } + x++; + x--; + }); + Console.WriteLine($"Count = {x}"); + return x; } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.03.SynchronizingWithMonitor.cs b/src/Chapter22/Listing22.03.SynchronizingWithMonitor.cs index ed41deefd..03dad38e5 100644 --- a/src/Chapter22/Listing22.03.SynchronizingWithMonitor.cs +++ b/src/Chapter22/Listing22.03.SynchronizingWithMonitor.cs @@ -1,72 +1,71 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_03 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_03; + +#region INCLUDE +using System; +using System.Threading; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.Threading; - using System.Threading.Tasks; + #region HIGHLIGHT + readonly static object _Sync = new object(); + #endregion HIGHLIGHT + static int _Total = int.MaxValue; + static int _Count = 0; - public class Program + public static int Main(string[] args) { - #region HIGHLIGHT - readonly static object _Sync = new object(); - #endregion HIGHLIGHT - static int _Total = int.MaxValue; - static int _Count = 0; + if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } + Console.WriteLine($"Increment and decrementing {_Total} times..."); - public static int Main(string[] args) - { - if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } - Console.WriteLine($"Increment and decrementing {_Total} times..."); + // Use Task.Factory.StartNew for .NET 4.0 + Task task = Task.Run(() => Decrement()); - // Use Task.Factory.StartNew for .NET 4.0 - Task task = Task.Run(() => Decrement()); - - // Increment - for(int i = 0; i < _Total; i++) + // Increment + for(int i = 0; i < _Total; i++) + { + #region HIGHLIGHT + bool lockTaken = false; + try { - #region HIGHLIGHT - bool lockTaken = false; - try - { - Monitor.Enter(_Sync, ref lockTaken); - _Count++; - } - finally + Monitor.Enter(_Sync, ref lockTaken); + _Count++; + } + finally + { + if(lockTaken) { - if(lockTaken) - { - Monitor.Exit(_Sync); - } + Monitor.Exit(_Sync); } - #endregion HIGHLIGHT } - - task.Wait(); - Console.WriteLine($"Count = {_Count}"); - return _Count; + #endregion HIGHLIGHT } - public static void Decrement() + task.Wait(); + Console.WriteLine($"Count = {_Count}"); + return _Count; + } + + public static void Decrement() + { + for(int i = 0; i < _Total; i++) { - for(int i = 0; i < _Total; i++) + #region HIGHLIGHT + bool lockTaken = false; + try { - #region HIGHLIGHT - bool lockTaken = false; - try - { - Monitor.Enter(_Sync, ref lockTaken); - _Count--; - } - finally + Monitor.Enter(_Sync, ref lockTaken); + _Count--; + } + finally + { + if(lockTaken) { - if(lockTaken) - { - Monitor.Exit(_Sync); - } + Monitor.Exit(_Sync); } - #endregion HIGHLIGHT } + #endregion HIGHLIGHT } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.04.SynchronizingWithLockKeyword.cs b/src/Chapter22/Listing22.04.SynchronizingWithLockKeyword.cs index 42cfd9148..838a9886d 100644 --- a/src/Chapter22/Listing22.04.SynchronizingWithLockKeyword.cs +++ b/src/Chapter22/Listing22.04.SynchronizingWithLockKeyword.cs @@ -1,53 +1,52 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_04; + +#region INCLUDE +using System; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.Threading.Tasks; + #region HIGHLIGHT + readonly static object _Sync = new object(); + #endregion HIGHLIGHT + static int _Total = int.MaxValue; + static int _Count = 0; - public class Program + public static int Main(string[] args) { - #region HIGHLIGHT - readonly static object _Sync = new object(); - #endregion HIGHLIGHT - static int _Total = int.MaxValue; - static int _Count = 0; + if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } + Console.WriteLine($"Increment and decrementing {_Total} times..."); - public static int Main(string[] args) - { - if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } - Console.WriteLine($"Increment and decrementing {_Total} times..."); + // Use Task.Factory.StartNew for .NET 4.0 + Task task = Task.Run(() => Decrement()); - // Use Task.Factory.StartNew for .NET 4.0 - Task task = Task.Run(() => Decrement()); - - // Increment - for (int i = 0; i < _Total; i++) + // Increment + for (int i = 0; i < _Total; i++) + { + #region HIGHLIGHT + lock (_Sync) { - #region HIGHLIGHT - lock (_Sync) - { - _Count++; - } - #endregion HIGHLIGHT + _Count++; } - - task.Wait(); - Console.WriteLine($"Count = {_Count}"); - return _Count; + #endregion HIGHLIGHT } - public static void Decrement() + task.Wait(); + Console.WriteLine($"Count = {_Count}"); + return _Count; + } + + public static void Decrement() + { + for (int i = 0; i < _Total; i++) { - for (int i = 0; i < _Total; i++) + #region HIGHLIGHT + lock (_Sync) { - #region HIGHLIGHT - lock (_Sync) - { - _Count--; - } - #endregion HIGHLIGHT + _Count--; } + #endregion HIGHLIGHT } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.05.AsyncMain.cs b/src/Chapter22/Listing22.05.AsyncMain.cs index 181467b15..1a03d5bd3 100644 --- a/src/Chapter22/Listing22.05.AsyncMain.cs +++ b/src/Chapter22/Listing22.05.AsyncMain.cs @@ -1,51 +1,50 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_05 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_05; + +#region INCLUDE +using System; +using System.Threading.Tasks; + +public class Program { - #region INCLUDE - using System; - using System.Threading.Tasks; + readonly static object _Sync = new object(); + static int _Total = int.MaxValue; + static int _Count = 0; - public class Program + #region HIGHLIGHT + public static async Task Main(string[] args) + #endregion HIGHLIGHT { - readonly static object _Sync = new object(); - static int _Total = int.MaxValue; - static int _Count = 0; + if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } + Console.WriteLine($"Increment and decrementing {_Total} times..."); - #region HIGHLIGHT - public static async Task Main(string[] args) - #endregion HIGHLIGHT - { - if (args?.Length > 0) { _ = int.TryParse(args[0], out _Total); } - Console.WriteLine($"Increment and decrementing {_Total} times..."); - - // Use Task.Factory.StartNew for .NET 4.0 - Task task = Task.Run(() => Decrement()); + // Use Task.Factory.StartNew for .NET 4.0 + Task task = Task.Run(() => Decrement()); - // Increment - for(int i = 0; i < _Total; i++) + // Increment + for(int i = 0; i < _Total; i++) + { + lock(_Sync) { - lock(_Sync) - { - _Count++; - } + _Count++; } - - #region HIGHLIGHT - await task; - #endregion HIGHLIGHT - Console.WriteLine($"Count = {_Count}"); - return _Count; } - static void Decrement() + #region HIGHLIGHT + await task; + #endregion HIGHLIGHT + Console.WriteLine($"Count = {_Count}"); + return _Count; + } + + static void Decrement() + { + for(int i = 0; i < _Total; i++) { - for(int i = 0; i < _Total; i++) + lock(_Sync) { - lock(_Sync) - { - _Count--; - } + _Count--; } } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.06.SynchronizingUsingInterlocked.cs b/src/Chapter22/Listing22.06.SynchronizingUsingInterlocked.cs index d16ed8e96..a8dfc8616 100644 --- a/src/Chapter22/Listing22.06.SynchronizingUsingInterlocked.cs +++ b/src/Chapter22/Listing22.06.SynchronizingUsingInterlocked.cs @@ -1,23 +1,22 @@ // Justification: Only partial implementation provided. #pragma warning disable IDE0051 // Remove unused private members -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_06 -{ - using System.Threading; - #region INCLUDE - public class SynchronizationUsingInterlocked - { - private static object? _Data; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_06; - // Initialize data if not yet assigned - public static void Initialize(object newValue) - { - // If _Data is null then set it to newValue - Interlocked.CompareExchange( - ref _Data, newValue, null); - } +using System.Threading; +#region INCLUDE +public class SynchronizationUsingInterlocked +{ + private static object? _Data; - // ... + // Initialize data if not yet assigned + public static void Initialize(object newValue) + { + // If _Data is null then set it to newValue + Interlocked.CompareExchange( + ref _Data, newValue, null); } - #endregion INCLUDE + + // ... } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.07.FiringEventNotification.cs b/src/Chapter22/Listing22.07.FiringEventNotification.cs index 333f1abec..baa90d689 100644 --- a/src/Chapter22/Listing22.07.FiringEventNotification.cs +++ b/src/Chapter22/Listing22.07.FiringEventNotification.cs @@ -1,37 +1,36 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_07 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_07; + +delegate void TemperatureChangedHandler(Program one, TemperatureEventArgs two); + +public class Program { - delegate void TemperatureChangedHandler(Program one, TemperatureEventArgs two); + private static readonly TemperatureChangedHandler OnTemperatureChanged = delegate { }; - public class Program + public void Main() { - private static readonly TemperatureChangedHandler OnTemperatureChanged = delegate { }; - - public void Main() + #region INCLUDE + // Not thread safe + #region HIGHLIGHT + if (OnTemperatureChanged != null) + #endregion HIGHLIGHT { - #region INCLUDE - // Not thread safe - #region HIGHLIGHT - if (OnTemperatureChanged != null) - #endregion HIGHLIGHT - { - // Call subscribers - OnTemperatureChanged( - this, new TemperatureEventArgs(value)); - } - #endregion INCLUDE + // Call subscribers + OnTemperatureChanged( + this, new TemperatureEventArgs(value)); } + #endregion INCLUDE + } - // Justification: Lowercase to simulate the value keyword from a setter. + // Justification: Lowercase to simulate the value keyword from a setter. #pragma warning disable IDE1006 // Naming Styles - public object? value { get; set; } - #pragma warning restore IDE1006 // Naming Styles - } + public object? value { get; set; } + #pragma warning restore IDE1006 // Naming Styles +} - class TemperatureEventArgs +class TemperatureEventArgs +{ + public TemperatureEventArgs(object? _) { - public TemperatureEventArgs(object? _) - { - // ... - } + // ... } } diff --git a/src/Chapter22/Listing22.08.ThreadSafeEventNotification.cs b/src/Chapter22/Listing22.08.ThreadSafeEventNotification.cs index 1919bac26..710332124 100644 --- a/src/Chapter22/Listing22.08.ThreadSafeEventNotification.cs +++ b/src/Chapter22/Listing22.08.ThreadSafeEventNotification.cs @@ -1,44 +1,43 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_08 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_08; + +delegate void TemperatureChangedHandler(Program one, TemperatureEventArgs two); + +class Program { - delegate void TemperatureChangedHandler(Program one, TemperatureEventArgs two); + private static TemperatureChangedHandler OnTemperatureChanged = delegate { }; - class Program + public void Main() { - private static TemperatureChangedHandler OnTemperatureChanged = delegate { }; - - public void Main() - { #if(!PreCSharp6) - OnTemperatureChanged?.Invoke( - this, new TemperatureEventArgs(value)); + OnTemperatureChanged?.Invoke( + this, new TemperatureEventArgs(value)); #else - #region INCLUDE - //... - TemperatureChangedHandler localOnChange = - OnTemperatureChanged; - if(localOnChange != null) - { - // Call subscribers - localOnChange( - this, new TemperatureEventArgs(value)); - } - //... - #endregion INCLUDE -#endif + #region INCLUDE + //... + TemperatureChangedHandler localOnChange = + OnTemperatureChanged; + if(localOnChange != null) + { + // Call subscribers + localOnChange( + this, new TemperatureEventArgs(value)); } + //... + #endregion INCLUDE +#endif + } - // Justification: Lowercase to simulate the value keyword form a stetter. + // Justification: Lowercase to simulate the value keyword form a stetter. #pragma warning disable IDE1006 // Naming Styles - public object? value { get; set; } + public object? value { get; set; } #pragma warning restore IDE1006 // Naming Styles - } +} - public class TemperatureEventArgs +public class TemperatureEventArgs +{ + public TemperatureEventArgs(object? _) { - public TemperatureEventArgs(object? _) - { - // ... - } + // ... } } diff --git a/src/Chapter22/Listing22.09.CreatingASingleInstanceApplication.cs b/src/Chapter22/Listing22.09.CreatingASingleInstanceApplication.cs index 8985d89e6..be36a1ad2 100644 --- a/src/Chapter22/Listing22.09.CreatingASingleInstanceApplication.cs +++ b/src/Chapter22/Listing22.09.CreatingASingleInstanceApplication.cs @@ -1,36 +1,35 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_09 -{ - #region INCLUDE - using System; - using System.Reflection; - using System.Threading; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_09; + +#region INCLUDE +using System; +using System.Reflection; +using System.Threading; - public class Program +public class Program +{ + public static void Main() { - public static void Main() - { - // Obtain the mutex name from the full - // assembly name. - string mutexName = - Assembly.GetEntryAssembly()!.FullName!; + // Obtain the mutex name from the full + // assembly name. + string mutexName = + Assembly.GetEntryAssembly()!.FullName!; - // firstApplicationInstance indicates - // whether this is the first - // application instance. - using Mutex mutex = new Mutex(false, mutexName, - out bool firstApplicationInstance); + // firstApplicationInstance indicates + // whether this is the first + // application instance. + using Mutex mutex = new Mutex(false, mutexName, + out bool firstApplicationInstance); - if (!firstApplicationInstance) - { - Console.WriteLine( - "This application is already running."); - } - else - { - Console.WriteLine("ENTER to shut down"); - Console.ReadLine(); - } + if (!firstApplicationInstance) + { + Console.WriteLine( + "This application is already running."); + } + else + { + Console.WriteLine("ENTER to shut down"); + Console.ReadLine(); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.10.WaitingForManualResetEventSlim.cs b/src/Chapter22/Listing22.10.WaitingForManualResetEventSlim.cs index 07112e370..4db3cb1e1 100644 --- a/src/Chapter22/Listing22.10.WaitingForManualResetEventSlim.cs +++ b/src/Chapter22/Listing22.10.WaitingForManualResetEventSlim.cs @@ -1,57 +1,56 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_10 -{ - #region INCLUDE - using System; - using System.Threading; - using System.Threading.Tasks; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_10; - public class Program - { - #region EXCLUDE - // Justification: Initialized at the start of Main. +#region INCLUDE +using System; +using System.Threading; +using System.Threading.Tasks; + +public class Program +{ + #region EXCLUDE + // Justification: Initialized at the start of Main. #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. - #endregion EXCLUDE - static ManualResetEventSlim _MainSignaledResetEvent; - static ManualResetEventSlim _DoWorkSignaledResetEvent; - #region EXCLUDE + #endregion EXCLUDE + static ManualResetEventSlim _MainSignaledResetEvent; + static ManualResetEventSlim _DoWorkSignaledResetEvent; + #region EXCLUDE #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. - #endregion EXCLUDE + #endregion EXCLUDE - public static void DoWork() - { - Console.WriteLine("DoWork() started...."); - #region HIGHLIGHT - _DoWorkSignaledResetEvent.Set(); - _MainSignaledResetEvent.Wait(); - #endregion HIGHLIGHT - Console.WriteLine("DoWork() ending...."); - } + public static void DoWork() + { + Console.WriteLine("DoWork() started...."); + #region HIGHLIGHT + _DoWorkSignaledResetEvent.Set(); + _MainSignaledResetEvent.Wait(); + #endregion HIGHLIGHT + Console.WriteLine("DoWork() ending...."); + } - public static void Main() + public static void Main() + { + using(_MainSignaledResetEvent = + new ManualResetEventSlim()) + using(_DoWorkSignaledResetEvent = + new ManualResetEventSlim()) { - using(_MainSignaledResetEvent = - new ManualResetEventSlim()) - using(_DoWorkSignaledResetEvent = - new ManualResetEventSlim()) - { - Console.WriteLine( - "Application started...."); - Console.WriteLine("Starting task...."); + Console.WriteLine( + "Application started...."); + Console.WriteLine("Starting task...."); - // Use Task.Factory.StartNew for .NET 4.0 - Task task = Task.Run(() => DoWork()); + // Use Task.Factory.StartNew for .NET 4.0 + Task task = Task.Run(() => DoWork()); - // Block until DoWork() has started - _DoWorkSignaledResetEvent.Wait(); - Console.WriteLine( - " Waiting while thread executes..."); - _MainSignaledResetEvent.Set(); - task.Wait(); - Console.WriteLine("Thread completed"); - Console.WriteLine( - "Application shutting down...."); - } + // Block until DoWork() has started + _DoWorkSignaledResetEvent.Wait(); + Console.WriteLine( + " Waiting while thread executes..."); + _MainSignaledResetEvent.Set(); + task.Wait(); + Console.WriteLine("Thread completed"); + Console.WriteLine( + "Application shutting down...."); } } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.11.UsingThreadLocalForThreadLocalStorage.cs b/src/Chapter22/Listing22.11.UsingThreadLocalForThreadLocalStorage.cs index 1f9b02a9f..d70634814 100644 --- a/src/Chapter22/Listing22.11.UsingThreadLocalForThreadLocalStorage.cs +++ b/src/Chapter22/Listing22.11.UsingThreadLocalForThreadLocalStorage.cs @@ -1,45 +1,44 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_11; + +#region INCLUDE +using System; +using System.Threading; + +public class Program { - #region INCLUDE - using System; - using System.Threading; + #region HIGHLIGHT + static ThreadLocal _Count = + new ThreadLocal(() => 0.01134); + #endregion HIGHLIGHT + public static double Count + { + get { return _Count.Value; } + set { _Count.Value = value; } + } - public class Program + public static void Main() { - #region HIGHLIGHT - static ThreadLocal _Count = - new ThreadLocal(() => 0.01134); - #endregion HIGHLIGHT - public static double Count - { - get { return _Count.Value; } - set { _Count.Value = value; } - } + Thread thread = new Thread(Decrement); + thread.Start(); - public static void Main() + // Increment + for(double i = 0; i < short.MaxValue; i++) { - Thread thread = new Thread(Decrement); - thread.Start(); - - // Increment - for(double i = 0; i < short.MaxValue; i++) - { - Count++; - } - thread.Join(); - Console.WriteLine("Main Count = {0}", Count); + Count++; } + thread.Join(); + Console.WriteLine("Main Count = {0}", Count); + } - public static void Decrement() + public static void Decrement() + { + Count = -Count; + for(double i = 0; i < short.MaxValue; i++) { - Count = -Count; - for(double i = 0; i < short.MaxValue; i++) - { - Count--; - } - Console.WriteLine( - "Decrement Count = {0}", Count); + Count--; } + Console.WriteLine( + "Decrement Count = {0}", Count); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.12.UsingThreadStaticAttribute.cs b/src/Chapter22/Listing22.12.UsingThreadStaticAttribute.cs index 7db039bdc..69ea19cea 100644 --- a/src/Chapter22/Listing22.12.UsingThreadStaticAttribute.cs +++ b/src/Chapter22/Listing22.12.UsingThreadStaticAttribute.cs @@ -1,42 +1,41 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_12 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_12; + +#region INCLUDE +using System; +using System.Threading; + +public class Program { - #region INCLUDE - using System; - using System.Threading; + [ThreadStatic] + static double _Count = 0.01134; + public static double Count + { + get { return Program._Count; } + set { Program._Count = value; } + } - public class Program + public static void Main() { - [ThreadStatic] - static double _Count = 0.01134; - public static double Count - { - get { return Program._Count; } - set { Program._Count = value; } - } + Thread thread = new Thread(Decrement); + thread.Start(); - public static void Main() + // Increment + for(int i = 0; i < short.MaxValue; i++) { - Thread thread = new Thread(Decrement); - thread.Start(); - - // Increment - for(int i = 0; i < short.MaxValue; i++) - { - Count++; - } - - thread.Join(); - Console.WriteLine("Main Count = {0}", Count); + Count++; } - public static void Decrement() + thread.Join(); + Console.WriteLine("Main Count = {0}", Count); + } + + public static void Decrement() + { + for(int i = 0; i < short.MaxValue; i++) { - for(int i = 0; i < short.MaxValue; i++) - { - Count--; - } - Console.WriteLine("Decrement Count = {0}", Count); + Count--; } + Console.WriteLine("Decrement Count = {0}", Count); } - #endregion INCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/Listing22.13.TaskDelayAsTimer.cs b/src/Chapter22/Listing22.13.TaskDelayAsTimer.cs index e873cf591..c3754f781 100644 --- a/src/Chapter22/Listing22.13.TaskDelayAsTimer.cs +++ b/src/Chapter22/Listing22.13.TaskDelayAsTimer.cs @@ -1,43 +1,42 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22.Listing22_13; + +#region INCLUDE +using System; +using System.Threading.Tasks; + +public class Pomodoro { - #region INCLUDE - using System; - using System.Threading.Tasks; + // ... - public class Pomodoro + private static async Task TickAsync( + System.Threading.CancellationToken token) { - // ... - - private static async Task TickAsync( - System.Threading.CancellationToken token) + for(int minute = 0; minute < 25; minute++) { - for(int minute = 0; minute < 25; minute++) + DisplayMinuteTicker(minute); + for(int second = 0; second < 60; second++) { - DisplayMinuteTicker(minute); - for(int second = 0; second < 60; second++) - { - await Task.Delay(1000, token); - if(token.IsCancellationRequested) - break; - DisplaySecondTicker(); - } + await Task.Delay(1000, token); if(token.IsCancellationRequested) break; + DisplaySecondTicker(); } + if(token.IsCancellationRequested) + break; } - #region EXCLUDE - private static void DisplaySecondTicker() - { - // ... - throw new NotImplementedException(); - } + } + #region EXCLUDE + private static void DisplaySecondTicker() + { + // ... + throw new NotImplementedException(); + } - private static void DisplayMinuteTicker(int minute) - { - // ... - throw new NotImplementedException(); - } - #endregion EXCLUDE + private static void DisplayMinuteTicker(int minute) + { + // ... + throw new NotImplementedException(); } - #endregion INCLUDE + #endregion EXCLUDE } +#endregion INCLUDE diff --git a/src/Chapter22/PiCalculation.cs b/src/Chapter22/PiCalculation.cs index bbf467dfc..2acd95bfb 100644 --- a/src/Chapter22/PiCalculation.cs +++ b/src/Chapter22/PiCalculation.cs @@ -3,58 +3,57 @@ using System.Threading.Tasks; using AddisonWesley.Michaelis.EssentialCSharp.Shared; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter22; + +partial class PiCalculation { - partial class PiCalculation + public void CalculateAsync( + int digits) { - public void CalculateAsync( - int digits) - { - CalculateAsync(digits, null); - } - public void CalculateAsync( - int digits, object? userState) - { - CalculateAsync( - digits, userState, default); - } - public void CalculateAsync( - int digits, - TState userState, - CancellationToken cancelToken) - { - Task.Factory.StartNew( - () => PiCalculator.Calculate(digits), cancelToken) - .ContinueWith( - continueTask => - { - CalculateCompleted?.Invoke(typeof(PiCalculator), - new CalculateCompletedEventArgs( - continueTask.Result, - continueTask.Exception, - cancelToken.IsCancellationRequested, - userState)); - return continueTask.Result; - }); - } - public event - EventHandler - CalculateCompleted = delegate { }; + CalculateAsync(digits, null); + } + public void CalculateAsync( + int digits, object? userState) + { + CalculateAsync( + digits, userState, default); + } + public void CalculateAsync( + int digits, + TState userState, + CancellationToken cancelToken) + { + Task.Factory.StartNew( + () => PiCalculator.Calculate(digits), cancelToken) + .ContinueWith( + continueTask => + { + CalculateCompleted?.Invoke(typeof(PiCalculator), + new CalculateCompletedEventArgs( + continueTask.Result, + continueTask.Exception, + cancelToken.IsCancellationRequested, + userState)); + return continueTask.Result; + }); + } + public event + EventHandler + CalculateCompleted = delegate { }; - public class CalculateCompletedEventArgs - : AsyncCompletedEventArgs + public class CalculateCompletedEventArgs + : AsyncCompletedEventArgs + { + public CalculateCompletedEventArgs( + string value, + Exception? error, + bool cancelled, + object? userState) + : base( + error, cancelled, userState) { - public CalculateCompletedEventArgs( - string value, - Exception? error, - bool cancelled, - object? userState) - : base( - error, cancelled, userState) - { - Result = value; - } - public string Result { get; private set; } + Result = value; } + public string Result { get; private set; } } } diff --git a/src/Chapter23/Listing23.01.DeclaringAnExternalMethod.cs b/src/Chapter23/Listing23.01.DeclaringAnExternalMethod.cs index 3383e3a38..3e6ffecbf 100644 --- a/src/Chapter23/Listing23.01.DeclaringAnExternalMethod.cs +++ b/src/Chapter23/Listing23.01.DeclaringAnExternalMethod.cs @@ -1,14 +1,13 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_01 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_01; + +#region INCLUDE +using System; +using System.Runtime.InteropServices; +public class VirtualMemoryManager { - #region INCLUDE - using System; - using System.Runtime.InteropServices; - public class VirtualMemoryManager - { - [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess")] - #region HIGHLIGHT - internal static extern IntPtr GetCurrentProcessHandle(); - #endregion HIGHLIGHT - } - #endregion INCLUDE -} \ No newline at end of file + [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess")] + #region HIGHLIGHT + internal static extern IntPtr GetCurrentProcessHandle(); + #endregion HIGHLIGHT +} +#endregion INCLUDE diff --git a/src/Chapter23/Listing23.04.UsingrefAndoutRatherThanPointers.cs b/src/Chapter23/Listing23.04.UsingrefAndoutRatherThanPointers.cs index b89cb1afe..ededbbd67 100644 --- a/src/Chapter23/Listing23.04.UsingrefAndoutRatherThanPointers.cs +++ b/src/Chapter23/Listing23.04.UsingrefAndoutRatherThanPointers.cs @@ -1,19 +1,18 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_04 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_04; + +using System; +using System.Runtime.InteropServices; +#region INCLUDE +public class VirtualMemoryManager { - using System; - using System.Runtime.InteropServices; - #region INCLUDE - public class VirtualMemoryManager - { - // ... - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool VirtualProtectEx( - IntPtr hProcess, IntPtr lpAddress, - IntPtr dwSize, uint flNewProtect, - #region HIGHLIGHT - ref uint lpflOldProtect); - #endregion HIGHLIGHT - } - #endregion INCLUDE -} \ No newline at end of file + // ... + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool VirtualProtectEx( + IntPtr hProcess, IntPtr lpAddress, + IntPtr dwSize, uint flNewProtect, + #region HIGHLIGHT + ref uint lpflOldProtect); + #endregion HIGHLIGHT +} +#endregion INCLUDE diff --git a/src/Chapter23/Listing23.06.Win32ErrorHandling.cs b/src/Chapter23/Listing23.06.Win32ErrorHandling.cs index 63938feea..41de41380 100644 --- a/src/Chapter23/Listing23.06.Win32ErrorHandling.cs +++ b/src/Chapter23/Listing23.06.Win32ErrorHandling.cs @@ -1,93 +1,92 @@ using System.Runtime.InteropServices; -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_06 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_06; + +#region INCLUDE +public class VirtualMemoryManager { - #region INCLUDE - public class VirtualMemoryManager + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr VirtualAllocEx( + IntPtr hProcess, + IntPtr lpAddress, + IntPtr dwSize, + AllocationType flAllocationType, + uint flProtect); + + // ... + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool VirtualProtectEx( + IntPtr hProcess, IntPtr lpAddress, + IntPtr dwSize, uint flNewProtect, + #region HIGHLIGHT + ref uint lpflOldProtect); + #endregion HIGHLIGHT + + [Flags] + private enum AllocationType : uint { - [DllImport("kernel32.dll", SetLastError = true)] - private static extern IntPtr VirtualAllocEx( - IntPtr hProcess, - IntPtr lpAddress, - IntPtr dwSize, - AllocationType flAllocationType, - uint flProtect); + #region EXCLUDE + Reserve, + Commit + #endregion EXCLUDE + } - // ... - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool VirtualProtectEx( - IntPtr hProcess, IntPtr lpAddress, - IntPtr dwSize, uint flNewProtect, - #region HIGHLIGHT - ref uint lpflOldProtect); - #endregion HIGHLIGHT + [Flags] + private enum ProtectionOptions + { + #region EXCLUDE + PageExecuteReadWrite + #endregion EXCLUDE + } - [Flags] - private enum AllocationType : uint - { - #region EXCLUDE - Reserve, - Commit - #endregion EXCLUDE - } + [Flags] + private enum MemoryFreeType + { + // ... + } - [Flags] - private enum ProtectionOptions - { - #region EXCLUDE - PageExecuteReadWrite - #endregion EXCLUDE - } + public static IntPtr AllocExecutionBlock( + int size, IntPtr hProcess) + { + IntPtr codeBytesPtr; + codeBytesPtr = VirtualAllocEx( + hProcess, IntPtr.Zero, + (IntPtr)size, + AllocationType.Reserve | AllocationType.Commit, + (uint)ProtectionOptions.PageExecuteReadWrite); - [Flags] - private enum MemoryFreeType + if (codeBytesPtr == IntPtr.Zero) { - // ... + #region HIGHLIGHT + throw new System.ComponentModel.Win32Exception(); + #endregion HIGHLIGHT } - public static IntPtr AllocExecutionBlock( - int size, IntPtr hProcess) + uint lpflOldProtect = 0; + if (!VirtualProtectEx( + hProcess, codeBytesPtr, + (IntPtr)size, + (uint)ProtectionOptions.PageExecuteReadWrite, + ref lpflOldProtect)) { - IntPtr codeBytesPtr; - codeBytesPtr = VirtualAllocEx( - hProcess, IntPtr.Zero, - (IntPtr)size, - AllocationType.Reserve | AllocationType.Commit, - (uint)ProtectionOptions.PageExecuteReadWrite); - - if (codeBytesPtr == IntPtr.Zero) - { - #region HIGHLIGHT - throw new System.ComponentModel.Win32Exception(); - #endregion HIGHLIGHT - } - - uint lpflOldProtect = 0; - if (!VirtualProtectEx( - hProcess, codeBytesPtr, - (IntPtr)size, - (uint)ProtectionOptions.PageExecuteReadWrite, - ref lpflOldProtect)) - { - #region HIGHLIGHT - throw new System.ComponentModel.Win32Exception(); - #endregion HIGHLIGHT - } - return codeBytesPtr; + #region HIGHLIGHT + throw new System.ComponentModel.Win32Exception(); + #endregion HIGHLIGHT } + return codeBytesPtr; + } - public static IntPtr AllocExecutionBlock(int size) - { - return AllocExecutionBlock( - size, GetCurrentProcessHandle()); - } - - #region EXCLUDE - public static IntPtr GetCurrentProcessHandle() - { - throw new NotImplementedException(); - } - #endregion EXCLUDE + public static IntPtr AllocExecutionBlock(int size) + { + return AllocExecutionBlock( + size, GetCurrentProcessHandle()); + } + + #region EXCLUDE + public static IntPtr GetCurrentProcessHandle() + { + throw new NotImplementedException(); } - #endregion INCLUDE -} \ No newline at end of file + #endregion EXCLUDE +} +#endregion INCLUDE diff --git a/src/Chapter23/Listing23.11.DesignatingACodeBlockForUnsafeCode.cs b/src/Chapter23/Listing23.11.DesignatingACodeBlockForUnsafeCode.cs index 9b20e1988..3fbf55888 100644 --- a/src/Chapter23/Listing23.11.DesignatingACodeBlockForUnsafeCode.cs +++ b/src/Chapter23/Listing23.11.DesignatingACodeBlockForUnsafeCode.cs @@ -1,17 +1,16 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_11 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_11; + +#region INCLUDE +public class Program { - #region INCLUDE - public class Program + static int Main(string[] args) { - static int Main(string[] args) + unsafe { - unsafe - { - #region EXCLUDE - return 0; - #endregion EXCLUDE - } + #region EXCLUDE + return 0; + #endregion EXCLUDE } } - #endregion INCLUDE -} \ No newline at end of file +} +#endregion INCLUDE diff --git a/src/Chapter23/Listing23.13.InvalidReferentTypeExample.cs b/src/Chapter23/Listing23.13.InvalidReferentTypeExample.cs index dbad6a012..f6507b677 100644 --- a/src/Chapter23/Listing23.13.InvalidReferentTypeExample.cs +++ b/src/Chapter23/Listing23.13.InvalidReferentTypeExample.cs @@ -1,10 +1,9 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_13 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_13; + +#region INCLUDE +struct ServiceStatus { - #region INCLUDE - struct ServiceStatus - { - int State; - string Description; // Description is a reference type - } - #endregion INCLUDE -} \ No newline at end of file + int State; + string Description; // Description is a reference type +} +#endregion INCLUDE diff --git a/src/Chapter23/Listing23.15.AfixedStatementWithoutAddressOrArrayIndexer.cs b/src/Chapter23/Listing23.15.AfixedStatementWithoutAddressOrArrayIndexer.cs index 2d6af05dc..2491cba30 100644 --- a/src/Chapter23/Listing23.15.AfixedStatementWithoutAddressOrArrayIndexer.cs +++ b/src/Chapter23/Listing23.15.AfixedStatementWithoutAddressOrArrayIndexer.cs @@ -1,16 +1,15 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_15 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_15; + +public unsafe class FixedState { - public unsafe class FixedState + public static void Main() { - public static void Main() + #region INCLUDE + byte[] bytes = new byte[24]; + fixed (byte* pData = bytes) { - #region INCLUDE - byte[] bytes = new byte[24]; - fixed (byte* pData = bytes) - { - // ... - } - #endregion INCLUDE + // ... } + #endregion INCLUDE } } \ No newline at end of file diff --git a/src/Chapter23/Listing23.17.ModifyingAnImmutableString.cs b/src/Chapter23/Listing23.17.ModifyingAnImmutableString.cs index 52f29425e..a5912a2d0 100644 --- a/src/Chapter23/Listing23.17.ModifyingAnImmutableString.cs +++ b/src/Chapter23/Listing23.17.ModifyingAnImmutableString.cs @@ -1,29 +1,28 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_17 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_17; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region INCLUDE + string text = "S5280ft"; + Console.Write("{0} = ", text); + unsafe // Requires /unsafe switch { - #region INCLUDE - string text = "S5280ft"; - Console.Write("{0} = ", text); - unsafe // Requires /unsafe switch + fixed(char* pText = text) { - fixed(char* pText = text) - { - char* p = pText; - *++p = 'm'; - *++p = 'i'; - *++p = 'l'; - *++p = 'e'; - *++p = ' '; - *++p = ' '; - } + char* p = pText; + *++p = 'm'; + *++p = 'i'; + *++p = 'l'; + *++p = 'e'; + *++p = ' '; + *++p = ' '; } - Console.WriteLine(text); - #endregion INCLUDE } + Console.WriteLine(text); + #endregion INCLUDE } } diff --git a/src/Chapter23/Listing23.18.ModifyingAnImmutableWithTheIndexOperatorInUnsafeCode.cs b/src/Chapter23/Listing23.18.ModifyingAnImmutableWithTheIndexOperatorInUnsafeCode.cs index 160ddf65f..c47fe57c3 100644 --- a/src/Chapter23/Listing23.18.ModifyingAnImmutableWithTheIndexOperatorInUnsafeCode.cs +++ b/src/Chapter23/Listing23.18.ModifyingAnImmutableWithTheIndexOperatorInUnsafeCode.cs @@ -1,28 +1,27 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_18 -{ - using System; +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_18; + +using System; - public class Program +public class Program +{ + public static void Main() { - public static void Main() + #region INCLUDE + string text = "S5280ft"; + Console.Write("{0} = ", text); + unsafe // Requires /unsafe switch { - #region INCLUDE - string text = "S5280ft"; - Console.Write("{0} = ", text); - unsafe // Requires /unsafe switch + fixed(char* pText = text) { - fixed(char* pText = text) - { - pText[1] = 'm'; - pText[2] = 'i'; - pText[3] = 'l'; - pText[4] = 'e'; - pText[5] = ' '; - pText[6] = ' '; - } + pText[1] = 'm'; + pText[2] = 'i'; + pText[3] = 'l'; + pText[4] = 'e'; + pText[5] = ' '; + pText[6] = ' '; } - Console.WriteLine(text); - #endregion INCLUDE } + Console.WriteLine(text); + #endregion INCLUDE } } diff --git a/src/Chapter23/Listing23.19.DirectlyAccessingAReferentTypesMembers.cs b/src/Chapter23/Listing23.19.DirectlyAccessingAReferentTypesMembers.cs index 8b9fac561..0d3e98e9d 100644 --- a/src/Chapter23/Listing23.19.DirectlyAccessingAReferentTypesMembers.cs +++ b/src/Chapter23/Listing23.19.DirectlyAccessingAReferentTypesMembers.cs @@ -1,35 +1,34 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_19 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_19; + +public class Program { - public class Program + public static void Main() { - public static void Main() + #region INCLUDE + unsafe { - #region INCLUDE - unsafe - { - Angle angle = new Angle(30, 18, 0); - Angle* pAngle = ∠ - System.Console.WriteLine("{0}° {1}' {2}\"", - #region HIGHLIGHT - pAngle->Hours, pAngle->Minutes, pAngle->Seconds); - #endregion HIGHLIGHT - } - #endregion INCLUDE + Angle angle = new Angle(30, 18, 0); + Angle* pAngle = ∠ + System.Console.WriteLine("{0}° {1}' {2}\"", + #region HIGHLIGHT + pAngle->Hours, pAngle->Minutes, pAngle->Seconds); + #endregion HIGHLIGHT } + #endregion INCLUDE } +} - public struct Angle +public struct Angle +{ + public Angle(short hours, short minutes, short seconds) + : this() { - public Angle(short hours, short minutes, short seconds) - : this() - { - Hours = hours; - Minutes = minutes; - Seconds = seconds; - } - - public short Hours { get; set; } - public short Minutes { get; set; } - public short Seconds { get; set; } + Hours = hours; + Minutes = minutes; + Seconds = seconds; } + + public short Hours { get; set; } + public short Minutes { get; set; } + public short Seconds { get; set; } } diff --git a/src/Chapter23/Listing23.20.DesignatingABlockForUnsafeCode.cs b/src/Chapter23/Listing23.20.DesignatingABlockForUnsafeCode.cs index 5018280c3..9b9e1b67c 100644 --- a/src/Chapter23/Listing23.20.DesignatingABlockForUnsafeCode.cs +++ b/src/Chapter23/Listing23.20.DesignatingABlockForUnsafeCode.cs @@ -1,267 +1,266 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_20 +namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter23.Listing23_20; + +#region INCLUDE +using System; +using System.Runtime.InteropServices; +using System.Text; + +public class Program { - #region INCLUDE - using System; - using System.Runtime.InteropServices; - using System.Text; + public unsafe delegate void MethodInvoker(byte* buffer); - public class Program + public unsafe static int Main() { - public unsafe delegate void MethodInvoker(byte* buffer); - - public unsafe static int Main() + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + unsafe { - unsafe - { - byte[] codeBytes = new byte[] { - 0x49, 0x89, 0xd8, // mov %rbx,%r8 - 0x49, 0x89, 0xc9, // mov %rcx,%r9 - 0x48, 0x31, 0xc0, // xor %rax,%rax - 0x0f, 0xa2, // cpuid - 0x4c, 0x89, 0xc8, // mov %r9,%rax - 0x89, 0x18, // mov %ebx,0x0(%rax) - 0x89, 0x50, 0x04, // mov %edx,0x4(%rax) - 0x89, 0x48, 0x08, // mov %ecx,0x8(%rax) - 0x4c, 0x89, 0xc3, // mov %r8,%rbx - 0xc3 // retq - }; + byte[] codeBytes = new byte[] { + 0x49, 0x89, 0xd8, // mov %rbx,%r8 + 0x49, 0x89, 0xc9, // mov %rcx,%r9 + 0x48, 0x31, 0xc0, // xor %rax,%rax + 0x0f, 0xa2, // cpuid + 0x4c, 0x89, 0xc8, // mov %r9,%rax + 0x89, 0x18, // mov %ebx,0x0(%rax) + 0x89, 0x50, 0x04, // mov %edx,0x4(%rax) + 0x89, 0x48, 0x08, // mov %ecx,0x8(%rax) + 0x4c, 0x89, 0xc3, // mov %r8,%rbx + 0xc3 // retq + }; - byte[] buffer = new byte[12]; + byte[] buffer = new byte[12]; - using (VirtualMemoryPtr codeBytesPtr = - new VirtualMemoryPtr(codeBytes.Length)) - { - Marshal.Copy( - codeBytes, 0, - codeBytesPtr, codeBytes.Length); + using (VirtualMemoryPtr codeBytesPtr = + new VirtualMemoryPtr(codeBytes.Length)) + { + Marshal.Copy( + codeBytes, 0, + codeBytesPtr, codeBytes.Length); - MethodInvoker method = Marshal.GetDelegateForFunctionPointer(codeBytesPtr); - fixed (byte* newBuffer = &buffer[0]) - { - method(newBuffer); - } + MethodInvoker method = Marshal.GetDelegateForFunctionPointer(codeBytesPtr); + fixed (byte* newBuffer = &buffer[0]) + { + method(newBuffer); } - Console.Write("Processor Id: "); - Console.WriteLine(ASCIIEncoding.ASCII.GetChars(buffer)); - } // unsafe - } - else - { - Console.WriteLine("This sample is only valid for Windows"); - } - return 0; + } + Console.Write("Processor Id: "); + Console.WriteLine(ASCIIEncoding.ASCII.GetChars(buffer)); + } // unsafe } - } - #endregion INCLUDE - - public class VirtualMemoryPtr : SafeHandle - { - public VirtualMemoryPtr(int memorySize) : - base(IntPtr.Zero, true) + else { - ProcessHandle = - VirtualMemoryManager.GetCurrentProcessHandle(); - MemorySize = (IntPtr)memorySize; - AllocatedPointer = - VirtualMemoryManager.AllocExecutionBlock( - memorySize, ProcessHandle); - Disposed = false; + Console.WriteLine("This sample is only valid for Windows"); } + return 0; + } +} +#endregion INCLUDE - public readonly IntPtr AllocatedPointer; - readonly IntPtr ProcessHandle; - readonly IntPtr MemorySize; - bool Disposed; +public class VirtualMemoryPtr : SafeHandle +{ + public VirtualMemoryPtr(int memorySize) : + base(IntPtr.Zero, true) + { + ProcessHandle = + VirtualMemoryManager.GetCurrentProcessHandle(); + MemorySize = (IntPtr)memorySize; + AllocatedPointer = + VirtualMemoryManager.AllocExecutionBlock( + memorySize, ProcessHandle); + Disposed = false; + } - public static implicit operator IntPtr( - VirtualMemoryPtr virtualMemoryPointer) - { - return virtualMemoryPointer.AllocatedPointer; - } + public readonly IntPtr AllocatedPointer; + readonly IntPtr ProcessHandle; + readonly IntPtr MemorySize; + bool Disposed; - // SafeHandle abstract member - public override bool IsInvalid - { - get - { - return Disposed; - } - } + public static implicit operator IntPtr( + VirtualMemoryPtr virtualMemoryPointer) + { + return virtualMemoryPointer.AllocatedPointer; + } - // SafeHandle abstract member - protected override bool ReleaseHandle() + // SafeHandle abstract member + public override bool IsInvalid + { + get { - return Disposed = VirtualMemoryManager.VirtualFreeEx(ProcessHandle, AllocatedPointer, MemorySize); + return Disposed; } } - class VirtualMemoryManager + // SafeHandle abstract member + protected override bool ReleaseHandle() { - [DllImport("kernel32.dll", SetLastError = true)] - private static extern IntPtr VirtualAllocEx( - IntPtr hProcess, - IntPtr lpAddress, - IntPtr dwSize, - AllocationType flAllocationType, - uint flProtect); + return Disposed = VirtualMemoryManager.VirtualFreeEx(ProcessHandle, AllocatedPointer, MemorySize); + } +} - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool VirtualProtectEx( - IntPtr hProcess, IntPtr lpAddress, - IntPtr dwSize, uint flNewProtect, - ref uint lpflOldProtect); +class VirtualMemoryManager +{ + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr VirtualAllocEx( + IntPtr hProcess, + IntPtr lpAddress, + IntPtr dwSize, + AllocationType flAllocationType, + uint flProtect); - [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess")] - internal static extern IntPtr GetCurrentProcessHandle(); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool VirtualProtectEx( + IntPtr hProcess, IntPtr lpAddress, + IntPtr dwSize, uint flNewProtect, + ref uint lpflOldProtect); - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool VirtualFreeEx( - IntPtr hProcess, IntPtr lpAddress, - IntPtr dwSize, IntPtr dwFreeType); + [DllImport("kernel32.dll", EntryPoint = "GetCurrentProcess")] + internal static extern IntPtr GetCurrentProcessHandle(); - public static bool VirtualFreeEx( - IntPtr hProcess, IntPtr lpAddress, - IntPtr dwSize) - { - bool result = VirtualFreeEx( - hProcess, lpAddress, dwSize, - (IntPtr)MemoryFreeType.Decommit); - if (!result) - { - throw new System.ComponentModel.Win32Exception(); - } - return result; - } + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool VirtualFreeEx( + IntPtr hProcess, IntPtr lpAddress, + IntPtr dwSize, IntPtr dwFreeType); - public static bool VirtualFreeEx( - IntPtr lpAddress, IntPtr dwSize) + public static bool VirtualFreeEx( + IntPtr hProcess, IntPtr lpAddress, + IntPtr dwSize) + { + bool result = VirtualFreeEx( + hProcess, lpAddress, dwSize, + (IntPtr)MemoryFreeType.Decommit); + if (!result) { - return VirtualFreeEx( - GetCurrentProcessHandle(), lpAddress, dwSize); + throw new System.ComponentModel.Win32Exception(); } + return result; + } + + public static bool VirtualFreeEx( + IntPtr lpAddress, IntPtr dwSize) + { + return VirtualFreeEx( + GetCurrentProcessHandle(), lpAddress, dwSize); + } + /// + /// The type of memory allocation. This parameter must + /// contain one of the following values. + /// + [Flags] + private enum AllocationType : uint + { /// - /// The type of memory allocation. This parameter must - /// contain one of the following values. + /// Allocates physical storage in memory or in the + /// paging file on disk for the specified reserved + /// memory pages. The function initializes the memory + /// to zero. /// - [Flags] - private enum AllocationType : uint - { - /// - /// Allocates physical storage in memory or in the - /// paging file on disk for the specified reserved - /// memory pages. The function initializes the memory - /// to zero. - /// - Commit = 0x1000, - /// - /// Reserves a range of the process's virtual address - /// space without allocating any actual physical - /// storage in memory or in the paging file on disk. - /// - Reserve = 0x2000, - /// - /// Indicates that data in the memory range specified by - /// lpAddress and dwSize is no longer of interest. The - /// pages should not be read from or written to the - /// paging file. However, the memory block will be used - /// again later, so it should not be decommitted. This - /// value cannot be used with any other value. - /// - Reset = 0x80000, - /// - /// Allocates physical memory with read-write access. - /// This value is solely for use with Address Windowing - /// Extensions (AWE) memory. - /// - Physical = 0x400000, - /// - /// Allocates memory at the highest possible address. - /// - TopDown = 0x100000, - } + Commit = 0x1000, + /// + /// Reserves a range of the process's virtual address + /// space without allocating any actual physical + /// storage in memory or in the paging file on disk. + /// + Reserve = 0x2000, + /// + /// Indicates that data in the memory range specified by + /// lpAddress and dwSize is no longer of interest. The + /// pages should not be read from or written to the + /// paging file. However, the memory block will be used + /// again later, so it should not be decommitted. This + /// value cannot be used with any other value. + /// + Reset = 0x80000, + /// + /// Allocates physical memory with read-write access. + /// This value is solely for use with Address Windowing + /// Extensions (AWE) memory. + /// + Physical = 0x400000, + /// + /// Allocates memory at the highest possible address. + /// + TopDown = 0x100000, + } + /// + /// The memory protection for the region of pages to be + /// allocated. + /// + [Flags] + private enum ProtectionOptions : uint + { /// - /// The memory protection for the region of pages to be - /// allocated. + /// Enables execute access to the committed region of + /// pages. An attempt to read or write to the committed + /// region results in an access violation. /// - [Flags] - private enum ProtectionOptions : uint - { - /// - /// Enables execute access to the committed region of - /// pages. An attempt to read or write to the committed - /// region results in an access violation. - /// - Execute = 0x10, - /// - /// Enables execute and read access to the committed - /// region of pages. An attempt to write to the - /// committed region results in an access violation. - /// - PageExecuteRead = 0x20, - /// - /// Enables execute, read, and write access to the - /// committed region of pages. + Execute = 0x10, + /// + /// Enables execute and read access to the committed + /// region of pages. An attempt to write to the + /// committed region results in an access violation. + /// + PageExecuteRead = 0x20, + /// + /// Enables execute, read, and write access to the + /// committed region of pages. - /// - PageExecuteReadWrite = 0x40, - // ... - } + /// + PageExecuteReadWrite = 0x40, + // ... + } + /// + /// The type of free operation + /// + [Flags] + private enum MemoryFreeType : uint + { /// - /// The type of free operation + /// Decommits the specified region of committed pages. + /// After the operation, the pages are in the reserved + /// state. /// - [Flags] - private enum MemoryFreeType : uint - { - /// - /// Decommits the specified region of committed pages. - /// After the operation, the pages are in the reserved - /// state. - /// - Decommit = 0x4000, - /// - /// Releases the specified region of pages. After this - /// operation, the pages are in the free state. - /// - Release = 0x8000 - } - - public static IntPtr AllocExecutionBlock( - int size, IntPtr hProcess) - { - IntPtr codeBytesPtr; - codeBytesPtr = VirtualAllocEx( - hProcess, IntPtr.Zero, - (IntPtr)size, - AllocationType.Reserve | AllocationType.Commit, - (uint)ProtectionOptions.PageExecuteReadWrite); + Decommit = 0x4000, + /// + /// Releases the specified region of pages. After this + /// operation, the pages are in the free state. + /// + Release = 0x8000 + } - if (codeBytesPtr == IntPtr.Zero) - { - throw new System.ComponentModel.Win32Exception(); - } + public static IntPtr AllocExecutionBlock( + int size, IntPtr hProcess) + { + IntPtr codeBytesPtr; + codeBytesPtr = VirtualAllocEx( + hProcess, IntPtr.Zero, + (IntPtr)size, + AllocationType.Reserve | AllocationType.Commit, + (uint)ProtectionOptions.PageExecuteReadWrite); - uint lpflOldProtect = 0; - if (!VirtualProtectEx( - hProcess, codeBytesPtr, - (IntPtr)size, - (uint)ProtectionOptions.PageExecuteReadWrite, - ref lpflOldProtect)) - { - throw new System.ComponentModel.Win32Exception(); - } - return codeBytesPtr; + if (codeBytesPtr == IntPtr.Zero) + { + throw new System.ComponentModel.Win32Exception(); } - public static IntPtr AllocExecutionBlock(int size) + uint lpflOldProtect = 0; + if (!VirtualProtectEx( + hProcess, codeBytesPtr, + (IntPtr)size, + (uint)ProtectionOptions.PageExecuteReadWrite, + ref lpflOldProtect)) { - return AllocExecutionBlock( - size, GetCurrentProcessHandle()); + throw new System.ComponentModel.Win32Exception(); } + return codeBytesPtr; + } + + public static IntPtr AllocExecutionBlock(int size) + { + return AllocExecutionBlock( + size, GetCurrentProcessHandle()); } } diff --git a/src/Chapter23/Program.cs b/src/Chapter23/Program.cs index e9205e996..e2e03a37a 100644 --- a/src/Chapter23/Program.cs +++ b/src/Chapter23/Program.cs @@ -1,9 +1,8 @@ -namespace Chapter21 +namespace Chapter21; + +class Program { - class Program + static void Main(string[] args) { - static void Main(string[] args) - { - } } } diff --git a/src/Shared/Cryptographer.cs b/src/Shared/Cryptographer.cs index b08d25421..92bcf0d58 100644 --- a/src/Shared/Cryptographer.cs +++ b/src/Shared/Cryptographer.cs @@ -1,168 +1,166 @@ using System.Security.Cryptography; using System.Threading.Tasks; -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public class Cryptographer : IDisposable { - public class Cryptographer : IDisposable + #region PROPERTIES + public SymmetricAlgorithm CryptoAlgorithm { get; } + #endregion PROPERTIES + + #region CONSTRUCTORS + public Cryptographer(SymmetricAlgorithm cryptoAlgoritym) { - #region PROPERTIES - public SymmetricAlgorithm CryptoAlgorithm { get; } - #endregion PROPERTIES + CryptoAlgorithm = cryptoAlgoritym; + } - #region CONSTRUCTORS - public Cryptographer(SymmetricAlgorithm cryptoAlgoritym) - { - CryptoAlgorithm = cryptoAlgoritym; - } + public Cryptographer() + : this(Aes.Create()) + { + } + #endregion CONSTRUCTORS - public Cryptographer() - : this(Aes.Create()) - { - } - #endregion CONSTRUCTORS + public byte[] Encrypt(string text) + { + return EncryptAsync(text).Result; + } - public byte[] Encrypt(string text) - { - return EncryptAsync(text).Result; - } + public async Task EncryptAsync(string text) + { + return await EncryptAsync(text, CryptoAlgorithm.CreateEncryptor()); + } - public async Task EncryptAsync(string text) - { - return await EncryptAsync(text, CryptoAlgorithm.CreateEncryptor()); - } + public async Task EncryptAsync(string text, Stream outputFileStream) + { + return await EncryptAsync(text, CryptoAlgorithm.CreateEncryptor(), outputFileStream); + } - public async Task EncryptAsync(string text, Stream outputFileStream) + static public async Task EncryptAsync(string plainText, byte[] key, byte[] iv) + { + byte[] encrypted; + // Create a new AesManaged. + using (AesManaged aes = new AesManaged()) { - return await EncryptAsync(text, CryptoAlgorithm.CreateEncryptor(), outputFileStream); + // Create encryptor + ICryptoTransform encryptor = aes.CreateEncryptor(key, iv); + // Create MemoryStream + encrypted = await EncryptAsync(plainText, encryptor); } + // Return encrypted data + return encrypted; + } - static public async Task EncryptAsync(string plainText, byte[] key, byte[] iv) - { - byte[] encrypted; - // Create a new AesManaged. - using (AesManaged aes = new AesManaged()) + private static async Task EncryptAsync(string plainText, ICryptoTransform encryptor) + { + using MemoryStream memoryStream = new MemoryStream(); + return await EncryptAsync(plainText, encryptor, memoryStream); + } + + private static async Task EncryptAsync(string plainText, ICryptoTransform encryptor, Stream outputStream) + { + byte[] encrypted; + MemoryStream memoryStream; + + // Create crypto stream using the CryptoStream class. This class is the key to encryption + // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream + // to encrypt + using (CryptoStream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)) + // Create StreamWriter and write data to a stream + using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) + { + await streamWriter.WriteAsync(plainText); + if (outputStream is MemoryStream) { - // Create encryptor - ICryptoTransform encryptor = aes.CreateEncryptor(key, iv); - // Create MemoryStream - encrypted = await EncryptAsync(plainText, encryptor); + streamWriter.Close(); + memoryStream = (MemoryStream)outputStream; } - // Return encrypted data - return encrypted; - } - - private static async Task EncryptAsync(string plainText, ICryptoTransform encryptor) - { - using MemoryStream memoryStream = new MemoryStream(); - return await EncryptAsync(plainText, encryptor, memoryStream); - } - - private static async Task EncryptAsync(string plainText, ICryptoTransform encryptor, Stream outputStream) - { - byte[] encrypted; - MemoryStream memoryStream; - - // Create crypto stream using the CryptoStream class. This class is the key to encryption - // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream - // to encrypt - using (CryptoStream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)) - // Create StreamWriter and write data to a stream - using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) + else { - await streamWriter.WriteAsync(plainText); - if (outputStream is MemoryStream) + using (memoryStream = new MemoryStream()) { - streamWriter.Close(); - memoryStream = (MemoryStream)outputStream; + outputStream.CopyTo(memoryStream); } - else - { - using (memoryStream = new MemoryStream()) - { - outputStream.CopyTo(memoryStream); - } - } - encrypted = memoryStream.ToArray(); } - - return encrypted; + encrypted = memoryStream.ToArray(); } - public string Decrypt(byte[] encryptedData) - { - return DecryptAsync(encryptedData).Result; - } + return encrypted; + } - public async Task DecryptAsync(byte[] encryptedData) - { - return await DecryptAsync(encryptedData, CryptoAlgorithm.CreateDecryptor()); - } + public string Decrypt(byte[] encryptedData) + { + return DecryptAsync(encryptedData).Result; + } - public async Task DecryptAsync(byte[] encryptedData, Stream outputStream) - { - await DecryptAsync(encryptedData, CryptoAlgorithm.CreateDecryptor(), outputStream); - } + public async Task DecryptAsync(byte[] encryptedData) + { + return await DecryptAsync(encryptedData, CryptoAlgorithm.CreateDecryptor()); + } - static public async Task DecryptAsync(byte[] encryptedData, byte[] key, byte[] iV) - { - string plaintext; - // Create AesManaged - using AesManaged aes = new AesManaged(); - // Create a decryptor - ICryptoTransform decryptor = aes.CreateDecryptor(key, iV); - // Create the streams used for decryption. - plaintext = await DecryptAsync(encryptedData, decryptor); - return plaintext; - } + public async Task DecryptAsync(byte[] encryptedData, Stream outputStream) + { + await DecryptAsync(encryptedData, CryptoAlgorithm.CreateDecryptor(), outputStream); + } - private static async Task DecryptAsync(byte[] encryptedData, ICryptoTransform decryptor) - { - using MemoryStream encryptedStream = new MemoryStream(encryptedData); - return await DecryptAsync(encryptedStream, decryptor); - } + static public async Task DecryptAsync(byte[] encryptedData, byte[] key, byte[] iV) + { + string plaintext; + // Create AesManaged + using AesManaged aes = new AesManaged(); + // Create a decryptor + ICryptoTransform decryptor = aes.CreateDecryptor(key, iV); + // Create the streams used for decryption. + plaintext = await DecryptAsync(encryptedData, decryptor); + return plaintext; + } - private static async Task DecryptAsync(byte[] encryptedData, ICryptoTransform decryptor, Stream outputStream) - { - using MemoryStream encryptedStream = new MemoryStream(encryptedData); - await DecryptAsync(encryptedStream, decryptor, outputStream); - } + private static async Task DecryptAsync(byte[] encryptedData, ICryptoTransform decryptor) + { + using MemoryStream encryptedStream = new MemoryStream(encryptedData); + return await DecryptAsync(encryptedStream, decryptor); + } - private static async Task DecryptAsync(Stream encryptedStream, ICryptoTransform decryptor) - { - // Create crypto stream - using CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read); - // Read crypto stream - using StreamReader reader = new StreamReader(cryptoStream); - return await reader.ReadToEndAsync(); - } + private static async Task DecryptAsync(byte[] encryptedData, ICryptoTransform decryptor, Stream outputStream) + { + using MemoryStream encryptedStream = new MemoryStream(encryptedData); + await DecryptAsync(encryptedStream, decryptor, outputStream); + } - private static async Task DecryptAsync(Stream encryptedStream, ICryptoTransform decryptor, Stream decryptedStream) - { - // Create crypto stream - using CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read); - await cryptoStream.CopyToAsync(decryptedStream); - } + private static async Task DecryptAsync(Stream encryptedStream, ICryptoTransform decryptor) + { + // Create crypto stream + using CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read); + // Read crypto stream + using StreamReader reader = new StreamReader(cryptoStream); + return await reader.ReadToEndAsync(); + } - #region IDisposable Members - bool Disposed { get; set; } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - protected virtual void Dispose(bool disposing) - { - if (Disposed) - return; + private static async Task DecryptAsync(Stream encryptedStream, ICryptoTransform decryptor, Stream decryptedStream) + { + // Create crypto stream + using CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read); + await cryptoStream.CopyToAsync(decryptedStream); + } - if (disposing) - { - CryptoAlgorithm.Dispose(); - } + #region IDisposable Members + bool Disposed { get; set; } + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + protected virtual void Dispose(bool disposing) + { + if (Disposed) + return; - Disposed = true; + if (disposing) + { + CryptoAlgorithm.Dispose(); } - #endregion - } + Disposed = true; + } + #endregion } diff --git a/src/Shared/DoWorkEventArgs.cs b/src/Shared/DoWorkEventArgs.cs index 5458e3f8a..5f6e05a3a 100644 --- a/src/Shared/DoWorkEventArgs.cs +++ b/src/Shared/DoWorkEventArgs.cs @@ -1,10 +1,9 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public class DoWorkEventArgs : EventArgs { - public class DoWorkEventArgs : EventArgs - { - public DoWorkEventArgs(object argument) { Argument = argument; } - public object Argument { get; } - public bool Cancel { get; set; } - public object? Result { get; set; } - } + public DoWorkEventArgs(object argument) { Argument = argument; } + public object Argument { get; } + public bool Cancel { get; set; } + public object? Result { get; set; } } diff --git a/src/Shared/NetCore.cs b/src/Shared/NetCore.cs index 63086b725..7c109a6fb 100644 --- a/src/Shared/NetCore.cs +++ b/src/Shared/NetCore.cs @@ -1,17 +1,16 @@ using System.Reflection; -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public static class NetCore { - public static class NetCore + public static string GetNetCoreVersion() { - public static string GetNetCoreVersion() - { - Assembly assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly; - string[] assemblyPath = assembly.Location!.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); - int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App"); - if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2) - return assemblyPath[netCoreAppIndex + 1]; - throw new Exception("Unable to determine .NET Core version."); - } + Assembly assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly; + string[] assemblyPath = assembly.Location!.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); + int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App"); + if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2) + return assemblyPath[netCoreAppIndex + 1]; + throw new Exception("Unable to determine .NET Core version."); } } diff --git a/src/Shared/PiCalculator+InternalPiDigitCalculator.cs b/src/Shared/PiCalculator+InternalPiDigitCalculator.cs index 7dee5d776..aea8ddc9e 100644 --- a/src/Shared/PiCalculator+InternalPiDigitCalculator.cs +++ b/src/Shared/PiCalculator+InternalPiDigitCalculator.cs @@ -1,179 +1,178 @@ -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public partial class PiCalculator { - public partial class PiCalculator + internal static class InternalPiDigitCalculator { - internal static class InternalPiDigitCalculator + #region Modulus + private static int MultiplyModulus(long left, long right, int modulus) { - #region Modulus - private static int MultiplyModulus(long left, long right, int modulus) - { - return (int)((left * right) % modulus); - } + return (int)((left * right) % modulus); + } - // return the inverse of x mod y - private static int InverseModulus(int left, int right) + // return the inverse of x mod y + private static int InverseModulus(int left, int right) + { + int q; + int u = left; + int v = right; + int a = 0; + int c = 1; + int t; + + do { - int q; - int u = left; - int v = right; - int a = 0; - int c = 1; - int t; - - do - { - q = v / u; + q = v / u; - t = c; - c = a - q * c; - a = t; + t = c; + c = a - q * c; + a = t; - t = u; - u = v - q * u; - v = t; - } - while (u != 0); + t = u; + u = v - q * u; + v = t; + } + while (u != 0); - a %= right; - if (a < 0) a = right + a; + a %= right; + if (a < 0) a = right + a; - return a; - } + return a; + } - // return (a^b) mod m - private static int PowerModulus(int left, int right, int modulus) + // return (a^b) mod m + private static int PowerModulus(int left, int right, int modulus) + { + int r = 1; + int aa = left; + + while (true) { - int r = 1; - int aa = left; + if ((right & 0x01) != 0) r = MultiplyModulus(r, aa, modulus); + right >>= 1; + if (right == 0) break; + aa = MultiplyModulus(aa, aa, modulus); + } - while (true) - { - if ((right & 0x01) != 0) r = MultiplyModulus(r, aa, modulus); - right >>= 1; - if (right == 0) break; - aa = MultiplyModulus(aa, aa, modulus); - } + return r; + } + #endregion - return r; - } - #endregion + #region Primes + // return true if num is prime + private static bool IsPrime(int num) + { + // not prime if divisible by two + if ((num % 2) == 0) return false; - #region Primes - // return true if num is prime - private static bool IsPrime(int num) + int max = (int)(Math.Sqrt(num)); + for (int i = 3; i <= max; i += 2) { - // not prime if divisible by two - if ((num % 2) == 0) return false; + if ((num % i) == 0) return false; + } - int max = (int)(Math.Sqrt(num)); - for (int i = 3; i <= max; i += 2) - { - if ((num % i) == 0) return false; - } + return true; + } - return true; + // return the prime number immediately after num + private static int NextPrime(int num) + { + do + { + num++; } + while (!IsPrime(num)); - // return the prime number immediately after num - private static int NextPrime(int num) + return num; + } + #endregion + + public static int ComputeSection(int startingDigit) + { + int av; + int vmax; + int N = (int)((startingDigit + 20) * Math.Log(10) / Math.Log(2)); + int num; + int den; + int kq; + int kq2; + int t; + int v; + int s; + double sum = 0.0; + + for (int a = 3; a <= (2 * N); a = NextPrime(a)) { - do - { - num++; - } - while (!IsPrime(num)); + vmax = (int)(Math.Log(2 * N) / Math.Log(a)); + av = 1; - return num; - } - #endregion + for (int i = 0; i < vmax; ++i) av *= a; - public static int ComputeSection(int startingDigit) - { - int av; - int vmax; - int N = (int)((startingDigit + 20) * Math.Log(10) / Math.Log(2)); - int num; - int den; - int kq; - int kq2; - int t; - int v; - int s; - double sum = 0.0; - - for (int a = 3; a <= (2 * N); a = NextPrime(a)) + s = 0; + num = 1; + den = 1; + v = 0; + kq = 1; + kq2 = 1; + + for (int k = 1; k <= N; ++k) { - vmax = (int)(Math.Log(2 * N) / Math.Log(a)); - av = 1; + t = k; + if (kq >= a) + { + do + { + t /= a; + --v; + } + while ((t % a) == 0); - for (int i = 0; i < vmax; ++i) av *= a; + kq = 0; + } - s = 0; - num = 1; - den = 1; - v = 0; - kq = 1; - kq2 = 1; + ++kq; + num = MultiplyModulus(num, t, av); - for (int k = 1; k <= N; ++k) + t = (2 * k - 1); + if (kq2 >= a) { - t = k; - if (kq >= a) + if (kq2 == a) { do { t /= a; - --v; + ++v; } while ((t % a) == 0); - - kq = 0; } - ++kq; - num = MultiplyModulus(num, t, av); - - t = (2 * k - 1); - if (kq2 >= a) - { - if (kq2 == a) - { - do - { - t /= a; - ++v; - } - while ((t % a) == 0); - } + kq2 -= a; + } - kq2 -= a; - } + den = MultiplyModulus(den, t, av); + kq2 += 2; - den = MultiplyModulus(den, t, av); - kq2 += 2; + if (v > 0) + { + t = InverseModulus(den, av); + t = MultiplyModulus(t, num, av); + t = MultiplyModulus(t, k, av); - if (v > 0) + for (int i = v; i < vmax; ++i) { - t = InverseModulus(den, av); - t = MultiplyModulus(t, num, av); - t = MultiplyModulus(t, k, av); - - for (int i = v; i < vmax; ++i) - { - t = MultiplyModulus(t, a, av); - } - s += t; - if (s >= av) s -= av; + t = MultiplyModulus(t, a, av); } + s += t; + if (s >= av) s -= av; } - - t = PowerModulus(10, startingDigit - 1, av); - s = MultiplyModulus(s, t, av); - sum = (sum + (double)s / (double)av) % 1.0; } - return (int)(sum * 1e9); + t = PowerModulus(10, startingDigit - 1, av); + s = MultiplyModulus(s, t, av); + sum = (sum + (double)s / (double)av) % 1.0; } + + return (int)(sum * 1e9); } } } \ No newline at end of file diff --git a/src/Shared/PiCalculator.cs b/src/Shared/PiCalculator.cs index fbce8f875..7371c2798 100644 --- a/src/Shared/PiCalculator.cs +++ b/src/Shared/PiCalculator.cs @@ -1,89 +1,88 @@ using System.Text; -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared; + +public static partial class PiCalculator { - public static partial class PiCalculator + const int Digits = 100; + #region Helper + public static string Pi() { - const int Digits = 100; - #region Helper - public static string Pi() - { - return Calculate(); - } + return Calculate(); + } - public static string Calculate(int digits = Digits) - { - return Calculate(digits, 0); - } + public static string Calculate(int digits = Digits) + { + return Calculate(digits, 0); + } - public static string Calculate(int digits, int startingAt) - { - DoWorkEventArgs eventArgs = new DoWorkEventArgs(digits); + public static string Calculate(int digits, int startingAt) + { + DoWorkEventArgs eventArgs = new DoWorkEventArgs(digits); - CalculatePi(typeof(PiCalculator), eventArgs, startingAt); - return (string)eventArgs.Result!; - } + CalculatePi(typeof(PiCalculator), eventArgs, startingAt); + return (string)eventArgs.Result!; + } - private static void CalculatePi( - object sender, DoWorkEventArgs eventArgs) + private static void CalculatePi( + object sender, DoWorkEventArgs eventArgs) + { + CalculatePi(sender, eventArgs, 0); + } + + private static void CalculatePi( + object sender, DoWorkEventArgs eventArgs, int startingAt) + { + int digits = (int)eventArgs.Argument; + + StringBuilder pi; + if(startingAt == 0) { - CalculatePi(sender, eventArgs, 0); + pi = new StringBuilder("3.", digits + 2); } - - private static void CalculatePi( - object sender, DoWorkEventArgs eventArgs, int startingAt) + else { - int digits = (int)eventArgs.Argument; - - StringBuilder pi; - if(startingAt == 0) - { - pi = new StringBuilder("3.", digits + 2); - } - else - { - pi = new StringBuilder(); - } + pi = new StringBuilder(); + } #if BackgroundWorkerThread - calculationWorker.ReportProgress(0, pi.ToString()); + calculationWorker.ReportProgress(0, pi.ToString()); #endif - // Calculate rest of pi, if required - if(digits > 0) + // Calculate rest of pi, if required + if(digits > 0) + { + for(int i = 0; i < digits; i += 9) { - for(int i = 0; i < digits; i += 9) - { - // Calculate next i decimal places - int nextDigit = InternalPiDigitCalculator.ComputeSection( - startingAt + i + 1); - int digitCount = Math.Min(digits - i, 9); - string ds = string.Format("{0:D9}", nextDigit); - pi.Append(ds.Substring(0, digitCount)); + // Calculate next i decimal places + int nextDigit = InternalPiDigitCalculator.ComputeSection( + startingAt + i + 1); + int digitCount = Math.Min(digits - i, 9); + string ds = string.Format("{0:D9}", nextDigit); + pi.Append(ds.Substring(0, digitCount)); - // Show current progress + // Show current progress #if BackgroundWorkerThread - calculationWorker.ReportProgress( - 0, ds.Substring(0, digitCount)); + calculationWorker.ReportProgress( + 0, ds.Substring(0, digitCount)); #endif #if BackgroundWorkerThread - // Check for cancellation - if (calculationWorker.CancellationPending) - { - // Need to set Cancel if you need to - // distinguish how a worker thread completed - // ie by checking - // RunWorkerCompletedEventArgs.Cancelled - eventArgs.Cancel = true; - break; - } -#endif + // Check for cancellation + if (calculationWorker.CancellationPending) + { + // Need to set Cancel if you need to + // distinguish how a worker thread completed + // ie by checking + // RunWorkerCompletedEventArgs.Cancelled + eventArgs.Cancel = true; + break; } +#endif } - - eventArgs.Result = pi.ToString(); } - #endregion + + eventArgs.Result = pi.ToString(); } + #endregion } diff --git a/src/Shared/Tests/PowerShellTestUtilities.cs b/src/Shared/Tests/PowerShellTestUtilities.cs index 5287db22f..9f1aedee0 100644 --- a/src/Shared/Tests/PowerShellTestUtilities.cs +++ b/src/Shared/Tests/PowerShellTestUtilities.cs @@ -1,82 +1,81 @@ using System.Runtime.InteropServices; using System.Diagnostics; -namespace AddisonWesley.Michaelis.EssentialCSharp.Shared.Tests +namespace AddisonWesley.Michaelis.EssentialCSharp.Shared.Tests; + +public class PowerShellTestUtilities { - public class PowerShellTestUtilities + private readonly static Mutex Mutext = new (false, typeof(PowerShellTestUtilities).FullName); + + public static bool WindowsEnvironment() { - private readonly static Mutex Mutext = new (false, typeof(PowerShellTestUtilities).FullName); - - public static bool WindowsEnvironment() - { - return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - } - - private readonly static Lazy _PowerShellCommand = new(() => + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + } + + private readonly static Lazy _PowerShellCommand = new(() => + { + string? powershellCommand = null; + // Verify that the PowerShell command executes successfully. + foreach(string command in + new string[]{ "pwsh", WindowsEnvironment() ? "PowerShell" : null!}.Where(item=> item is not null)) { - string? powershellCommand = null; - // Verify that the PowerShell command executes successfully. - foreach(string command in - new string[]{ "pwsh", WindowsEnvironment() ? "PowerShell" : null!}.Where(item=> item is not null)) + try { - try - { - Process powershell = Process.Start(command, "-Version"); - powershell.WaitForExit(); - if (powershell.ExitCode == 0) - { - powershellCommand = command; - break; - } - } - catch (System.ComponentModel.Win32Exception) + Process powershell = Process.Start(command, "-Version"); + powershell.WaitForExit(); + if (powershell.ExitCode == 0) { - powershellCommand = null; + powershellCommand = command; + break; } } - return powershellCommand; - }); - public static int RunPowerShellScript(string scriptPath, string arguments) => - RunPowerShellScript(scriptPath, arguments, out string _); + catch (System.ComponentModel.Win32Exception) + { + powershellCommand = null; + } + } + return powershellCommand; + }); + public static int RunPowerShellScript(string scriptPath, string arguments) => + RunPowerShellScript(scriptPath, arguments, out string _); - public static int RunPowerShellScript(string scriptPath, string arguments, out string psOutput) + public static int RunPowerShellScript(string scriptPath, string arguments, out string psOutput) + { + try { - try + Mutext.WaitOne(); + if (PowerShellCommand is null) { - Mutext.WaitOne(); - if (PowerShellCommand is null) - { - throw new InvalidOperationException("PowerShell is not installed"); - } - - if (!System.IO.File.Exists(scriptPath)) - { - throw new ArgumentException($"scriptPath, '{scriptPath}', not found.", nameof(scriptPath)); - } - - using var powerShell = new Process(); - powerShell.StartInfo.RedirectStandardOutput = true; - powerShell.StartInfo.RedirectStandardError = true; - powerShell.StartInfo.FileName = PowerShellCommand; - powerShell.StartInfo.Arguments = $"-noprofile -command \"{scriptPath} {arguments}\""; - powerShell.Start(); - psOutput = powerShell.StandardOutput.ReadToEnd(); - string errorOutput = powerShell.StandardError.ReadToEnd(); - if (errorOutput.Length > 0) - { - psOutput += $"{Environment.NewLine}ERROR: {Environment.NewLine}{errorOutput}"; - } - powerShell.WaitForExit(); + throw new InvalidOperationException("PowerShell is not installed"); + } - return powerShell.ExitCode; + if (!System.IO.File.Exists(scriptPath)) + { + throw new ArgumentException($"scriptPath, '{scriptPath}', not found.", nameof(scriptPath)); } - finally + + using var powerShell = new Process(); + powerShell.StartInfo.RedirectStandardOutput = true; + powerShell.StartInfo.RedirectStandardError = true; + powerShell.StartInfo.FileName = PowerShellCommand; + powerShell.StartInfo.Arguments = $"-noprofile -command \"{scriptPath} {arguments}\""; + powerShell.Start(); + psOutput = powerShell.StandardOutput.ReadToEnd(); + string errorOutput = powerShell.StandardError.ReadToEnd(); + if (errorOutput.Length > 0) { - Mutext.ReleaseMutex(); + psOutput += $"{Environment.NewLine}ERROR: {Environment.NewLine}{errorOutput}"; } - } + powerShell.WaitForExit(); - public static string? PowerShellCommand => _PowerShellCommand.Value; - public static bool PowerShellNotInstalled => _PowerShellCommand.Value is null; + return powerShell.ExitCode; + } + finally + { + Mutext.ReleaseMutex(); + } } + + public static string? PowerShellCommand => _PowerShellCommand.Value; + public static bool PowerShellNotInstalled => _PowerShellCommand.Value is null; }