void prevCodeExamples() { Person [] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } /* WriteLine("Use Person's IComparable implementation to sort:"); * Array.Sort ( people ); * * foreach ( var person in people ) * { * WriteLine($"{person.Name}"); * } */ WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // var t = new Thing(); // t.Data = 42; // WriteLine($"Thing: {t.Process("42")}"); var gt = new GenericThing <int>(); gt.Data = 42; WriteLine($"GenericThing: {gt.Process("42")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); // Using structures. WriteLine("\nWorking with structures..."); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); }
static void Main(string[] args) { var p1 = new Person(); p1.Name = "Bob Smith"; p1.DateOfBirth = new System.DateTime(1965, 12, 22); WriteLine($"{p1.Name} was born on {p1.DateOfBirth:dddd, d MMMM yyyy}"); var p2 = new Person { Name = "Alice Jones", DateOfBirth = new DateTime(1998, 3, 17) }; WriteLine($"{p2.Name} was born on {p2.DateOfBirth:d MMM yy}"); p1.BucketList = WondersOfTheAncientWorld.HangingGardenOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus; // p1.BucketList = (WondersOfTheAncientWorld)18; WriteLine($"{p1.Name}'s bucket list is {p1.BucketList}"); p1.Children.Add(new Person { Name = "Alfred" }); p1.Children.Add(new Person { Name = "Zoe" }); WriteLine( $"{p1.Name} has {p1.Children.Count} children:" ); for (int child = 0; child < p1.Children.Count; child++) { WriteLine($" {p1.Children[child].Name}"); } BankAccount.InterestRate = 0.012M; var ba1 = new BankAccount(); ba1.AccountName = "Mrs. Jones"; ba1.Balance = 2400; WriteLine($"{ba1.AccountName} earned {ba1.Balance * BankAccount.InterestRate:C} interest."); var ba2 = new BankAccount(); ba2.AccountName = "Ms. Gerrier"; ba2.Balance = 98; WriteLine($"{ba2.AccountName} earned {ba2.Balance * BankAccount.InterestRate:C} interest."); WriteLine($"{p1.Name} is a {Person.Species}"); // WriteLine($"{p1.Name} is a {p1.Species}"); WriteLine($"{p1.Name} was born on {p1.HomePlanet}"); var p3 = new Person(); WriteLine($"{p3.Name} was instantiated at {p3.Instantiated:hh:mm:ss} on {p3.Instantiated:dddd, d MMMM yyyy}"); var p4 = new Person("Aziz"); WriteLine($"{p4.Name} was instantiated at {p4.Instantiated:hh:mm:ss} on {p4.Instantiated:dddd, d MMMM yyyy}"); p1.WriteToConsole(); WriteLine(p1.GetOrigin()); Tuple <string, int> fruit4 = p1.GetFruitCS4(); WriteLine($"There are {fruit4.Item2} {fruit4.Item1}."); (string, int)fruit7 = p1.GetFruitCS7(); WriteLine($"{fruit7.Item1}, {fruit7.Item2} there are."); var fruitNamed = p1.GetNamedFruit(); WriteLine($"Are there {fruitNamed.Number} {fruitNamed.Name}?"); var thing1 = ("Neville", 4); WriteLine( $"{thing1.Item1} has {thing1.Item2} children." ); var thing2 = (p1.Name, p1.Children.Count); WriteLine( $"{thing2.Name} has {thing2.Count} children." ); (string fruitName, int fruitNumber) = p1.GetFruitCS7(); WriteLine($"Deconstructed: {fruitName}, {fruitNumber}"); WriteLine(p1.SayHello()); WriteLine(p1.SayHello("Emily")); WriteLine(p1.OptionalParameters()); WriteLine(p1.OptionalParameters("Jump!", 98.5)); WriteLine(p1.OptionalParameters(number: 52.7, command: "Hide!")); WriteLine(p1.OptionalParameters("Poke!", active: false)); int a = 10; int b = 20; int c = 30; WriteLine($"Before: a = {a}, b = {b}, c = {c}"); p1.PassingParameters(a, ref b, out c); WriteLine($"After: a = {a}, b = {b}, c = {c}"); // simplified C# 7 syntax for out parameters int d = 10; int e = 20; WriteLine($"Before: d = {d}, e = {e}, f doesn't exist yet!"); p1.PassingParameters(d, ref e, out int f); WriteLine($"After: d = {d}, e = {e}, f = {f}"); var sam = new Person { Name = "Sam", DateOfBirth = new DateTime(1972, 1, 27) }; WriteLine(sam.Origin); WriteLine(sam.Greeting); WriteLine(sam.Age); sam.FavoriteIceCream = "Chocolate Fudge"; WriteLine($"Sam's favorite ice-cream flavor is {sam.FavoriteIceCream}."); sam.FavoritePrimaryColor = "Red"; WriteLine($"Sam's favorite primary color is {sam.FavoritePrimaryColor}."); sam.Children.Add(new Person { Name = "Charlie" }); sam.Children.Add(new Person { Name = "Ella" }); WriteLine($"Sam's first child is {sam.Children[0].Name}"); WriteLine($"Sam's second child is {sam.Children[1].Name}"); WriteLine($"Sam's first child is {sam[0].Name}"); WriteLine($"Sam's second child is {sam[1].Name}"); var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine($"{mary.Name}'s first child is named \"{mary.Children[0].Name}\"."); WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t = new Thing(); t.Data = 42; WriteLine($"Thing: {t.Process("42")}"); var gt = new GenericThing <int>(); gt.Data = 42; WriteLine($"GenericThing: {gt.Process("42")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); Employee e1 = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; e1.WriteToConsole(); e1.EmployeeCode = "JJ001"; e1.HireDate = new DateTime(2014, 11, 23); WriteLine($"{e1.Name} was hired on {e1.HireDate:dd/MM/yy}"); WriteLine(e1.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee e2 = (Employee)aliceInPerson; // do something with e2 } Employee e3 = aliceInPerson as Employee; if (e3 != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // do something with e3 } try { e1.TimeTravel(new DateTime(1999, 12, 31)); e1.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine($"{email1} is a valid e-mail address: {email1.isValidEmail()}."); WriteLine($"{email2} is a valid e-mail address: {email2.isValidEmail()}."); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children"); WriteLine($"{mary.Name} has {mary.Children.Count} children"); WriteLine($"{jill.Name} has {jill.Children.Count} children"); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name ); // calling the local function WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; int count = 0; do { harry.Poke(); count++; }while (count < 4); // Comparing objects when sorting Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" }, }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("User Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square(number2)); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.HireDate = new DateTime(2014, 11, 23); john.EmployeeCode = "JJ001"; WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); WriteLine(john.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123", DateOfBirth = new DateTime(1970, 12, 12) }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); /* * When a method is overridden with virtual and override, the compiler is smart * enough to know that although the variable is declared as a Person class, the object * itself is an Employee class and, therefore, the Employee implementation of ToString * is called. */ // Explicit casting (safely) if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; } // can also use `as` keyword and check for null Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { // we can do something with aliceAsEmployee WriteLine($"{nameof(aliceInPerson)} AS an Employee"); } try { aliceInEmployee.TimeTravel(new DateTime(1999, 12, 31)); aliceInEmployee.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1) ); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2) ); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // метод вызова экземпляра var baby1 = mary.ProcreateWith(harry); // метод статического вызова var baby2 = Person.Procreate(harry, jill); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine($"{mary.Name}'s first child is named\"{mary.Children[0].Name}\"."); string s1 = "Hello "; string s2 = "World!"; string s3 = string.Concat(s1, s2); WriteLine(s3); // => Hello World! // вызов оператора var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{harry.Name}'s first child is named\"{harry.Children[0].Name}\"."); WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t = new Thing(); t.Data = 42; WriteLine($"Thing: {t.Process("42")}"); var gt = new GenericThing <int>(); gt.Data = 42; WriteLine($"GenericThing: {gt.Process("42")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X},{dv3.Y})"); Employee e1 = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; e1.WriteToConsole(); e1.EmployeeCode = "JJ001"; e1.HireDate = new DateTime(2014, 11, 23); WriteLine($"{e1.Name} was hired on {e1.HireDate:dd/MM/yy}"); WriteLine(e1.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); //Employee e2 = (Employee)aliceInPerson; if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee e2 = (Employee)aliceInPerson; // действия с e2 } Employee e3 = aliceInPerson as Employee; if (e3 != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // действия с e3 } try { e1.TimeTravel(new DateTime(1999, 12, 31)); e1.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine($"{email1} is a valid e-mail address: {StringExtensions.IsValidEmail(email1)}."); WriteLine($"{email2} is a valid e-mail address: {StringExtensions.IsValidEmail(email2)}."); WriteLine($"{email1} is a valid e-mail address:{email1.IsValidEmail()}."); WriteLine($"{email2} is a valid e-mail address:{email2.IsValidEmail()}."); }
static void Main(string[] args) { // Test Casting // Person(base) casting to Employee(sub Class) is not ok int a = 100; WriteLine("INT type:{0}", a.GetType().Name); Person edwardInPerson = new Person { Name = "Edward" }; if (edwardInPerson is Employee) { Employee edwardInEmployee = (Employee)edwardInPerson; } else { WriteLine("EdwardInPerson is Not Employee, is {0}", edwardInPerson.GetType()); } Employee YvonneInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; if (YvonneInEmployee is Employee) { Person YvonneInPerson = YvonneInEmployee; // Employee casting to Person is ok WriteLine("YvonneInPerson is {0}", YvonneInPerson.GetType()); WriteLine("YvonneInEmployee is {0}", YvonneInEmployee.GetType()); if (YvonneInPerson is Employee) { WriteLine("YvonneInPerson is actually Employee!"); Employee explicitYvonneInPersonToEmployee = (Employee)YvonneInPerson; } } else { WriteLine("YvonneInEmployee is Not Employee, is {0}", edwardInPerson.ToString()); } var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; var may = new Person { Name = "May" }; // call instance method var baby1 = mary.ProcreateWith(harry); baby1.Name = "Gary"; // call static method var baby2 = Person.Procreate(harry, jill); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); for (int i = 0; i < harry.Children.Count; i++) { WriteLine( format: "{0}'s {1} child is named \"{2}\".", harry.Name, i, harry.Children[i].Name); } var baby3 = may * jill; WriteLine($"{may.Name} has {may.Children.Count} children."); for (int i = 0; i < jill.Children.Count; i++) { WriteLine( format: "{0}'s {1} child is named \"{2}\".", jill.Name, i, jill.Children[i].Name); } WriteLine($"Person Factorial 5: {may.Factorial(5)}"); // event handler: assign Event Listener // When assigning a method to a delegate field, you should not use the simple assignment operator as we did in the preceding example, and as shown in the following code: // harry.Shout = Harry_Shout; // If the Shout delegate field was already referencing one or more methods, by assigning a method, it would replace all the others. With delegates that are used for events // we usuallywant to make sure that a programmer only ever uses either the += operator or the -= operator to assign and remove methods: harry.Shout += Harry_Shout; harry.Shout += Harry_Shout; harry.Shout += Harry_Shout; harry.Shout -= Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); // ----------------------------------- // test coommon interface[Icomparable/Icompare] by Array.Sort // ----------------------------------- Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($" {person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($" {person.Name}"); } for (int idx = 0; idx < people.Length; idx++) { WriteLine($" {people[idx].Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($" {person.Name}"); } // Defining interfaces with default implementations var dvdplayer = new DvdPlayer(); dvdplayer.Play(); dvdplayer.Pause(); dvdplayer.Stop(); dvdplayer.Error(); dvdplayer.Error2(); var odvdplayer = new DvdPlayerOld(); odvdplayer.Play(); odvdplayer.Pause(); odvdplayer.Stop(); odvdplayer.Error(); // ---------------------------- // test generics Type: // ---------------------------- // Note the following: // • When instantiating an instance of a generic type, the developer must pass a // type parameter. In this example, we pass int as the type parameter for gt1 and // string as the type parameter for gt2, so wherever T appears in the GenericThing // class, it is replaced with int and string. // • When setting the Data field and passing the input parameter, the compiler // enforces the use of an int value, such as 42, for // ---------------------------- var gt1 = new GenericThing <int> { Data = 42 }; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); string number1 = "4.5"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); // ---------------------------------- // test struct // ---------------------------------- var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X},{dv3.Y})"); // ---------------------------------- // test Inheriting from classes // ---------------------------------- Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; WriteLine(format: "employee {0}'s birthdate is {1:dddd,dd/MM/yy}", john.Name, john.DateOfBirth); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); john.WriteToConsole(); WriteLine("=============================="); WriteLine("Testing polymorphic"); WriteLine("=============================="); Person pMike = new Person(); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; // implicit casting Person aliceInPerson = aliceInEmployee; // When a method is hidden with new, the compiler is not smart enough to know that the object is an Employee, so it calls the WriteToConsole method in Person. aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); // When a method is overridden with virtual and override, the compiler is smart enough to know that although the variable is declared as a Person class, the object itself is an Employee class and, therefore, the Employee implementation of ToString is called. WriteLine($"Person ToString():{pMike.ToString()}"); WriteLine($"aliceInEmployee ToString():{aliceInEmployee.ToString()}"); WriteLine($"aliceInPerson ToString():{aliceInPerson.ToString()}"); WriteLine("=============================="); WriteLine("Testing casting"); WriteLine("=============================="); // checking type before casting using "is" if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; explicitAlice.WriteToConsole(); } else { WriteLine($"{nameof(pMike)} is NOT an Employee"); } // checking type before casting using "is" if (pMike is Employee) { WriteLine($"{nameof(pMike)} IS an Employee"); Employee explicitMike = (Employee)pMike; explicitMike.WriteToConsole(); } else { WriteLine($"{nameof(pMike)} is NOT an Employee"); } // checking type before casting using "as" WriteLine("*** checking type before casting using 'is'"); Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); } else { WriteLine($"{nameof(aliceInPerson)} NOT as an Employee"); } // checking type before casting using "as" WriteLine("*** checking type before casting using 'as'"); Employee mikeAsEmployee = pMike as Employee; if (mikeAsEmployee != null) { WriteLine($"{nameof(pMike)} AS an Employee"); } else { WriteLine($"{nameof(pMike)} NOT as an Employee"); } try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } try { john.TimeTravel2(new DateTime(1999, 12, 31)); john.TimeTravel2(new DateTime(1950, 12, 25)); } catch (Exception ex) { WriteLine(ex.Message); } WriteLine("==================================="); WriteLine("Testing Extending types when you can't inherit"); WriteLine("==================================="); string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine("*** Using static methods to reuse functionality"); WriteLine(format: "{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1)); WriteLine(format: "{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2)); WriteLine("*** Using extension methods to reuse functionality"); WriteLine(format: "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine(format: "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { #region POO Stuff var baltazar = new Person(); baltazar.Name = "Baltazar"; WriteLine(baltazar.ToString()); var leo = new Person(); leo.Name = "Leonardo"; leo.DateOfBirth = new DateTime(1990, 12, 22); WriteLine($"{leo.Name} was born in {leo.DateOfBirth: d MMMM yyyy}"); var layla = new Person { Name = "Layla", DateOfBirth = new DateTime(1980, 3, 7), FavoriteWonder = WondersOfTheWorld.ColossusOfRhodes }; WriteLine($"{layla.Name} was born in {layla.DateOfBirth: d MMMM yyyy}"); baltazar.FavoriteWonder = WondersOfTheWorld.HangingGardensOfBabylon; baltazar.Children.Add(new Person { Name = "Alfred" }); baltazar.Children.Add(new Person { Name = "Sakura Kinomot Desu" }); WriteLine($"{baltazar.Name} has {baltazar.Children.Count} children :"); for (int child = 0; child < baltazar.Children.Count; child++) { WriteLine($"{baltazar.Children[child].Name}"); } BankAccount.InterestRate = 0.012M; var leoAccount = new BankAccount(); leoAccount.AccountName = "Mister Leo"; leoAccount.Balance = 3400; WriteLine($"{leoAccount.AccountName} earned {leoAccount.Balance * BankAccount.InterestRate:C} interest"); var laylaAccount = new BankAccount(); laylaAccount.AccountName = "Miss Layla"; laylaAccount.Balance = 3400; WriteLine($"{laylaAccount.AccountName} earned {laylaAccount.Balance * BankAccount.InterestRate:C} interest"); var blankPerson = new Person(); WriteLine($"{blankPerson.Name} of {blankPerson.HomePlanet} was created {blankPerson.Instantiated}"); var martian = new Person("Marvin", "Mars"); WriteLine($"{martian.Name} of {martian.HomePlanet} was created {martian.Instantiated}"); #endregion #region Procreate var ana = new Person { Name = "Ana" }; var tiberio = new Person { Name = "Tiberio" }; var vicente = new Person { Name = "Vicente" }; // call instance method var baby1 = ana.ProceateWith(tiberio); baby1.Name = "NoPalindromo"; // static call var baby2 = Person.Procreate(vicente, ana); // ussing overload operator var baby3 = ana * tiberio; WriteLine($"{ana.Name} has {ana.Children.Count} children"); WriteLine($"{tiberio.Name} has {tiberio.Children.Count} children"); WriteLine($"{vicente.Name} has {vicente.Children.Count} children"); WriteLine($"{ana.Name}'s first child is named \"{ana.Children[1].Name}\"."); #endregion #region TestLocal Functions WriteLine($"5! is {Person.Factorial(5)}"); #endregion #region Delegates var p1 = new Person(); int answer = p1.MethodICall("Something"); // Instance the delegate var d = new DelegateWithMatch(p1.MethodICall); // call the instance int answer2 = d("Tuple"); WriteLine(answer); WriteLine(answer2); ana.Shout += Ana_Shout; ana.Shout += Tiberio_Shout; ana.Shout += Luis_Shout; ana.Poke(); ana.Poke(); ana.Poke(); ana.Poke(); ana.Poke(); #endregion #region IComparable Person[] people = { new Person { Name = "Juan" }, new Person { Name = "Ana" }, new Person { Name = "Tiberio" }, new Person { Name = "Estela" }, new Person { Name = "Diego" }, }; WriteLine("Initial List"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Using IComparable Interface"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } #endregion #region IComparer WriteLine("Use IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } #endregion #region Using Generics var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer : {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string : {t1.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"Generic Thing with an integer : {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"Generic Thing with an integer : {gt2.Process("apple")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); #endregion #region Using struct var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"{dv3.X} , {dv3.Y}"); #endregion /* * using (Animal a = new Animal()) * { * // code Animal * } * * .... compiler converts previous code into something like this ... * Animal a = new Animal(); * try * { * // code Animal * } * finally * { * if (a != null ) a.Dispose(); * } */ #region Using inheritance Employee luis = new Employee { Name = "Luis Adrian", DateOfBirth = new DateTime(1990, 12, 12) }; luis.WriteToConsole(); luis.EmployeeCode = "1300851"; luis.HireDate = new DateTime(2011, 11, 23); WriteLine($"{luis.Name} was hired in {luis.HireDate:dd/MM/yy}"); WriteLine(luis.ToString()); #endregion #region catching own PersonExceptions try { luis.TimeTravel(new DateTime(1999, 12, 31)); luis.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } #endregion }
static void Main(string[] args) { var harry = new Person("Harry"); var mary = new Person("Mary"); var jill = new Person("Jill"); var baby1 = mary.ProcreateWith(harry); var baby2 = Person.Procreate(harry, jill); // multiply operator overloaded with the Person class: var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is called {1}", arg0: harry.Name, arg1: harry.Children[0].Name ); WriteLine($"5! is {Person.Factorial(5)}"); // assign the method defined in this program to the delegate field // note: delegates are multicast so can assign multiple delegates to a single delegate field although no control as to order called // so could have used += operator instead of just the = assignment operator (book page 189) harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); // BOOK: page 192 INTERFACES Person[] people = { new Person("Simon"), new Person("Jenny"), new Person("Adam"), new Person("Richard") }; WriteLine("People unsorted: "); foreach (var person in people) { Write($"{person.Name} "); } WriteLine(); WriteLine("People sorted - uses IComparable implementation to sort: "); Array.Sort(people); foreach (var person in people) { Write($"{person.Name} "); } WriteLine(); WriteLine("People sorted - uses PersonComparer (implements IComparer) class sort: "); Array.Sort(people, new PersonComparer()); foreach (var person in people) { Write($"{person.Name} "); } WriteLine(); // BOOK: page 198 making types safely reusable with GENERICS var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with an string: {t2.Process("apple")}"); // on instantiating instance of generic type, must pass a type parameter var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with an string: {gt2.Process("apple")}"); string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <byte>(number2)); var vector1 = new DisplacementVector(3, 4); var vector2 = new DisplacementVector(-2, 1); var vector3 = vector1 + vector2; WriteLine($"vector3: {vector3.X}, {vector3.Y}"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy} with code {john.EmployeeCode}"); WriteLine(john.ToString()); WriteLine(); // BOOK: page 212 Understanding polymorphism --------------------------------------------------------------------- // implicit casting section **** // an instance of a derived type (Employee) can be stored in a variable of the base type (Person) - IMPLICIT CASTING Employee aliceEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person alicePerson = aliceEmployee; // IMPLICIT casting WriteLine("Understanding Polymorphism section: "); WriteLine("alicePerson has just been assigned to aliceEmployee i.e. alicePerson = aliceEmployee"); WriteLine(); WriteLine("Now calling aliceEmployee.WriteToConsole(), then alicePerson.WriteToConsole()"); aliceEmployee.WriteToConsole(); // Employee.WriteToConsole(): Alice was born on 01/01/01 and hired on 01/01/01 alicePerson.WriteToConsole(); // Person.WriteToConsole(): Alice was born on a Monday WriteLine("Calling aliceEmployee.ToString(): " + aliceEmployee.ToString()); // Employee.ToString(): Alice's code is AA123 WriteLine("Calling alicePerson.ToString(): " + alicePerson.ToString()); // Employee.ToString(): Alice's code is AA123 // explicit casting section - and avoiding Casting Exceptions two options: use 'is' or 'as' keywords **** // use keyword 'is' if (alicePerson is Employee) { WriteLine($"{nameof(alicePerson)} IS an Employee - because of earlier assignment: alicePerson = aliceEmployee"); // safe to cast Employee explicitAlice = (Employee)alicePerson; } Employee aliceAsEmployee = alicePerson as Employee; // keyword 'as' used to explicity cast --> need to check for null though if (aliceAsEmployee != null) { WriteLine($"{nameof(alicePerson)} AS an Employee - because of earlier assignment: Employee aliceAsEmployee = alicePerson as Employee"); } // BOOK: page 216 Inheriting exceptions --------------------------------------------------------------------- try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // BOOK: page 218 Extending types when you cannot inherit (sealed) --------------------------------------------------------------------- string email1 = "*****@*****.**"; string email2 = "test&test.com"; WriteLine("{0} is a valid email address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1)); WriteLine("{0} is a valid email address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2)); WriteLine("{0} is a valid email address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine("{0} is a valid email address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var jill = new Person { Name = "Jill" }; var mary = new Person { Name = "Mary" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); // using local function method WriteLine($"5! is {Person.Factorial(5)}"); // using delegates WriteLine("harry shouts"); harry.Shout += Harry_Shout; for (int i = 0; i < 4; i++) { harry.Poke(); } // using interfaces Person[] people = { new Person { Name = "Simon" }, new Person { Name = "George" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementatin to sort: "); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } // using PersonComparer.cs WriteLine("Use PersonComparer's IComparer implementatin to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // Utilizing Thing.cs class for genetics var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); // thing is currently flexible because any type can be set for Data and input parameters. // We can fix that using Generics. See GenericThing class. var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "Banana"; WriteLine($"GeneticThing with a string: {gt2.Process("Banana")}"); // working with generic methods string number1 = "4"; WriteLine("{0} squared is {1}.", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); // Working with Struct types var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X},{dv2.Y}) = ({dv3.X},{dv3.Y})"); // using class inherittance Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1996, 10, 1) }; john.WriteToConsole(); // using new WriteToConsole from Employee.cs john.EmployeeCode = "JJ1001"; john.HireDate = new DateTime(2015, 11, 23); WriteLine($"{john.Name} was hired on: {john.HireDate:dd/MM/yy}."); WriteLine(john.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA332" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); // explicit casting // Employee explicitAlice = aliceInPerson; // fails as we cannot cast Person as Employee // Employee explicitAlice = (Employee)aliceInPerson; // this could lead to InvalidCastException // instead use a if statement if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; // safely do someting with explicitAlice } // you may also use AS to explicitly cast Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // do something with aliceAsEmployee } // in person class, we created our own exception PersonException which has a message try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // using StringExtensions string email1 = "*****@*****.**"; string email2 = "not$email.com"; WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call the instance method var baby1 = mary.ProcreateWith(harry); // call the static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children. "); WriteLine($"{mary.Name} has {mary.Children.Count} children. "); WriteLine($"{jill.Name} has {jill.Children.Count} children. "); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name ); WriteLine($"5! is {Person.Factorial(5)}"); // defining and hanlding delegates harry.Shout = Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" }, }; foreach (var person in people) { WriteLine($"{person.Name}"); } // Use Person's IComparable implmentation to sort: WriteLine("Use Person's IComparable implementatjoin to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // working with generic types // pre C# 2.0 var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); // C# 2.0 var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); // working with generic methods string number1 = "4"; WriteLine( format: "{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1) ); byte number2 = 3; WriteLine( format: "{0} squared is {1}", arg0: number2, arg1: Squarer.Square <byte>(number2) ); // working with struct types var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); // Inheriting from classes Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); john.WriteToConsole(); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yyyy}"); WriteLine(john.ToString()); // understanding polymorphism Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); // Employee.WriteToConsole() aliceInPerson.WriteToConsole(); // Person.WriteToConsole() WriteLine(aliceInEmployee.ToString()); // Employee ToString() WriteLine(aliceInPerson.ToString()); // Employee override ToString() Employee explicitAlice = (Employee)aliceInPerson; // same as below //Employee aliceAsEmployee = aliceInPerson as Employee; // same as above if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); } // inheriting expceptions try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // using static methods to reuse functionality // public bool IsValidEmail(this string input) //public static bool IsValidEmail(this string input) string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine( format: "{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1) ); WriteLine( format: "{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2) ); // using extension methods to reuse functionality (see LINQ for powerful uses of extensions) //public static bool IsValidEmail(this string input) WriteLine( format: "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail() ); WriteLine( format: "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail() ); }
// --------------- Event Examples --------------- // private static void Harry_Shout(object sender, EventArgs e) // { // Person p = (Person)sender; // System.Console.WriteLine($"{p.Name} is angry level {p.AngerLevel}"); // } // private static void Harry_Shout2(object sender, EventArgs e) // { // System.Console.WriteLine($"Blub"); // } static void Main() { // --------------- Generics Examples --------------- var t1 = new Thing(); t1.Data = 42; System.Console.WriteLine(t1.Process(42)); var t2 = new Thing(); t2.Data = "blub"; System.Console.WriteLine(t1.Process("blub")); var gt1 = new GenericThing <int>(); gt1.Data = 42; System.Console.WriteLine(gt1.Process(42)); var gt2 = new GenericThing <string>(); gt2.Data = "blub"; System.Console.WriteLine(gt2.Process("blub")); byte number = (byte)3; System.Console.WriteLine(Squarer.Square(number)); // --------------- Interfaces Examples --------------- // Person[] people = // { // new Person{ Name = "Olli"}, // new Person{ Name = "Lena"}, // new Person{ Name = "Zwu"}, // new Person{ Name = "Sigi"} // }; // Array.Sort(people); // foreach (var person in people) // { // WriteLine(person.Name); // } // Array.Sort(people, new PersonComparer()); // foreach (var person in people) // { // WriteLine(person.Name); // } // --------------- Event Examples --------------- // var harry = new Person { Name = "Harry" }; // harry.Shout += Harry_Shout; // harry.Shout += Harry_Shout2; // harry.Poke(); // harry.Poke(); // harry.Poke(); // harry.Poke(); // harry.Poke(); // var res = Person.Factorial(3); // System.Console.WriteLine(res); // Person Olli = new Person { Name = "Olli", DateOfBirth = new DateTime(1983, 12, 17) }; // Person Lena = new Person { Name = "Lena", DateOfBirth = new DateTime(1986, 09, 07) }; // var zwu = Person.Procreate(Olli, Lena); // var zwu2 = Olli * Lena; // System.Console.WriteLine($"{Olli.Children.Count} children: {zwu.Name} and {zwu2.Name}"); }
static void Chapter06() { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); var baby3 = harry * mary; WriteLine($"{mary.Name} has {mary.Children.Count} children"); WriteLine($"{harry.Name} has {harry.Children.Count} children"); WriteLine($"{jill.Name} has {jill.Children.Count} children"); WriteLine($"{mary.Name}'s first child is named \"{mary.Children[0].Name}\"."); // factorial with local function WriteLine($"5! is {Person.Factorial(5)}"); // Delegate example code var p1 = new Person("Delegate"); // normal way int answer = p1.MethodIWantToCall(p1.Name); // assign defined delegate function to variable var d = new DelegateWithMatchingSignature(p1.MethodIWantToCall); int delegatedAnswer = d("Frog"); WriteLine($"Delegated Answer: {delegatedAnswer}"); // delegate example harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); // Demonstrating Interfaces Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial List of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } // Using Custom IComparer implementation WriteLine("Use PersonComparers IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // not using generics - generates warning - comparison not valid var t = new Thing(); t.Data = 42; WriteLine($"Thing: {t.Process("42")}"); // using generics - define type in <brackets> var gt = new GenericThing <int>(); gt.Data = 42; WriteLine($"GenericThing: {gt.Process("42")}"); // using generic methods in non-generic class string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); // Using Structs var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); // Using Employee (inheriting from Person) Employee e1 = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; e1.WriteToConsole(); e1.EmployeeCode = "JJ001"; e1.HireDate = new DateTime(2014, 11, 23); WriteLine($"{e1.Name} was hired on {e1.HireDate:dd/MM/yy}"); // uses System.Object.ToString() until overriden. WriteLine(e1.ToString()); // demonstrate difference between polymorphism and non-polymorphism // "<blank> new" = non-polymorhpic // "virtual override" = polymorphic Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); // doesn't use the WriteToConsole override aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); // still uses overriden method in Employee Class WriteLine(aliceInPerson.ToString()); // checking class is type we expect it to be. if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an employee"); Employee e2 = (Employee)aliceInPerson; // do something with e2 } // or, convert is possible, if unavailable as returns null Employee e3 = aliceInPerson as Employee; if (e3 != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); } // use custom exception try { e1.TimeTravel(new DateTime(1999, 12, 31)); e1.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // adding methods to string string email1 = "*****@*****.**"; string email2 = "pamela&test.com"; WriteLine($"{email1} is a valid e-mail address: {email2.IsValidEmail()}"); WriteLine($"{email2} is a valid e-mail address: {email1.IsValidEmail()}"); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); string s1 = "Hello "; string s2 = "World!"; // string s3 = string.Concat(s1, s2); string s3 = s1 + s2; WriteLine(s3); WriteLine($"5! is {Person.Factorial(5)}"); var p1 = new Person(); var answer1 = p1.MethodIWantToCall("Frog"); var d = new DelegateWithMatchingSignature(new Person().MethodIWantToCall); var answer2 = d("Frog"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort: "); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({ dv3.X}, { dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd / MM / yy}"); string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // метод вызова экземпляра var baby1 = mary.ProcreateWith(harry); // метод статического вызова var baby2 = Person.Procreate(harry, jill); // вызов оператора var baby3 = harry * mary; WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine($"{mary.Name}'s first child is named \"{mary.Children[0].Name}\"."); WriteLine($"5! is {Person.Factorial(5)}"); //TODO FAILED DELEGATE var p1 = new Person { Name = "Crybaby" }; var d = new DelegateWithMatchingSignature(p1.MethodIWantToCall); int answer2 = d("Frog"); // Crate an instance of the delegate, pointing to the logging function. // This delegate will then be passed to the Process() function. LogHandler myLogger = new LogHandler(Logger); Person.Process(myLogger); //TODO EVENT HANDLER harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); // INTERFACES Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } //TODO Arrat.Sort принимать компаратор вторым параметром // который реализует интерфейс IComparer? WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } //TODO Создание универсальных типов var t = new Thing(); t.Data = 42; WriteLine($"Thing: {t.Process("42")}"); var gt = new GenericThing <int>(); gt.Data = 42; WriteLine($"GenericThing: {gt.Process("42")}"); //TODO Создание универсального метода string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square<byte>(number2)}"); //TODO Определение структур var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X},{dv3.Y})"); // Наследование классов Employee e1 = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; e1.WriteToConsole(); e1.EmployeeCode = "JJ001"; e1.HireDate = new DateTime(2014, 11, 23); WriteLine($"{e1.Name} was hired on {e1.HireDate:dd/MM/yy}"); WriteLine(e1.ToString()); //TODO Что происходит на при определении Person aliceInPerson? //TODO а если object aliceInEmployee = new Employee { Name = "Alice"}; Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); //Явное приведение if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee e2 = (Employee)aliceInPerson; // действия с e2 } Employee e3 = aliceInPerson as Employee; if (e3 != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // действия с e3 } //Наследование исключений try { e1.TimeTravel(new DateTime(1999, 12, 31)); e1.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } //Расширение типов при невозможности наследования string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine($"{email1} is a valid e-mail address: {StringExtensions.IsValidEmail(email1)}."); WriteLine($"{email2} is a valid e-mail address: {StringExtensions.IsValidEmail(email2)}."); //Extension methods WriteLine($"{email1} is a valid e-mail address: {email1.IsValidEmail()}."); WriteLine($"{email2} is a valid e-mail address: {email2.IsValidEmail()}."); }
private static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); baby1.Name = "Gary"; // call static method var baby2 = Person.Procreate(harry, jill); WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( "{0}'s first child is named \"{1}\".", harry.Name, harry.Children[0].Name); // call static method var baby3 = Person.Procreate(harry, jill); // call an operator var baby4 = harry * mary; WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; //add method to delegate field harry.Poke(); harry.Poke(); harry.Poke(); //trigger event handler harry.Poke(); Person[] people = { new() { Name = "Simon" }, new() { Name = "Jenny" }, new() { Name = "Adam" }, new() { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($" {person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); //now C# will use our custom compare function from Person class foreach (var person in people) { WriteLine($" {person.Name}"); } //sorting using PersonComparer.cs WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($" {person.Name}"); } var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); //with our generic method, we can use any valid type var number1 = "4"; WriteLine("{0} squared is {1}", number1, Squarer.Square(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", number2, Squarer.Square(number2)); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); var john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); //overriden to string method WriteLine(john.ToString()); //now were gonna compare non polymorphic inheritance vs polymorphic inheritance var aliceInEmployee = new Employee //implicit casting { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); //calls person function despite being employee //its better to use the virtual and override keyword tha new keyword, this allows the compiler to use the proper methods WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); var explicitAlice = (Employee)aliceInPerson; //explicit casting try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } var email1 = "*****@*****.**"; var email2 = "ian&test.com"; WriteLine( "{0} is a valid e-mail address: {1}", email1, email1.IsValidEmail()); WriteLine( "{0} is a valid e-mail address: {1}", email2, email2.IsValidEmail()); //the isValidEmail method appears in intellisense, since the class and method are setup as an extension for strings }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); // Working with generic methods string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; //call instance method var baby1 = mary.ProcreateWith(harry); //call static method var baby2 = Person.Procreate(harry, jill); //call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); WriteLine($"5! is {Person.Factorial(5)}"); var p1 = new Person { Name = "Joe" }; int answer = p1.MethodIWantToCall("Frog"); WriteLine($"instance->{answer}"); var d = new DelegateWithMatchingSignature(p1.MethodIWantToCall); int answer2 = d("Frog"); WriteLine($"delegate->{answer2}"); harry.Shout += Harry_Shout; harry.Poked(); harry.Poked(); harry.Poked(); harry.Poked(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Cathy" }, new Person { Name = "Judy" }, new Person { Name = "Adam" } }; WriteLine("initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable to implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer to implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); WriteLine($"{gt1.ToString()}"); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); string number1 = "4"; WriteLine("{0} squuared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); var dv1 = new DisplacementVector(2, 5); var dv2 = new DisplacementVector(-1, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X},{dv1.Y}) + ({dv2.X},{dv2.Y}) = ({dv3.X},{dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:yyyy/MMM/dd}"); john.WriteToConsole(); WriteLine(john.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} is an Employee"); Employee explicitAlice = (Employee)aliceInPerson; } Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceAsEmployee)} as an Employee"); } try{ john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 20)); }catch (PersonException ex) { WriteLine(ex.Message); } string email1 = "*****@*****.**"; string email2 = "inst&test.com"; WriteLine("{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtension.IsValidEmail(email1)); WriteLine("{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtension.IsValidEmail(email2)); WriteLine("{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine("{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; //call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); WriteLine($"{harry.Name} has {harry.Children.Count} children"); WriteLine($"{mary.Name} has {mary.Children.Count} children"); WriteLine($"{jill.Name} has {jill.Children.Count} children"); WriteLine(format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); // call an operator var baby3 = harry * mary; // call method with internal local function WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); harry.Start += Receive_Call; harry.ReceiveCall(); harry.ReceiveCall(); harry.ReceiveCall(); harry.ReceiveCall(); // Interfaces IComparable (allows arrays and collection to be sorted) Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } // Compare Names using IComparer Interfaces WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // Generics var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); // Working with generic methods string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); // Memory Management var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); // Inheriting from classes Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); WriteLine(john.ToString()); // Overriding methods Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); // Casting // Not Safe an Invalid Cast exception could appear // Employee explicitAlice = (Employee)aliceInPerson; // is keyword if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; // safetily do something with explicitAlice } // as keyword Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an employee"); // do something with aliceAsEmployee } // Custom Exception try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // Extension Methods string email1 = "*****@*****.**"; email1.ExtensionParameter("Test"); string email2 = "ian&test.com"; WriteLine("{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1)); WriteLine("{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2)); // statements to use extension methods WriteLine("{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine("{0} is a valid e-mail address: {1}", arg0: email1, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // Implementing functionality using methods and operators // call instance method var baby1 = mary.ProcreateWith(harry); baby1.Name = "Gary"; // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine( format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); // Implementing functionality using local functions WriteLine($"5! is {Person.Factorial(5)}"); // Raising and handling events harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); // Comparing objects when sorting Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($" {person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($" {person.Name}"); } // Comparing objects using a separate class WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } // Working with generic types var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); // Working with generic methods string number1 = "4"; WriteLine("{0} squared is {1}", arg0: number1, arg1: Squarer.Square <string>(number1)); byte number2 = 3; WriteLine("{0} squared is {1}", arg0: number2, arg1: Squarer.Square(number2)); // Working with struct types var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); // Inheriting from classes Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); // Extending classes john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); // Overriding members WriteLine(john.ToString()); // Understanding polymorphism Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); // Explicit casting if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; // safely do something with explicitAlice } Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // do something with aliceInEmployee } // Inheriting exceptions try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // Using static methods to reuse functionality string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: StringExtensions.IsValidEmail(email1)); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: StringExtensions.IsValidEmail(email2)); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }
static void Main(string[] args) { var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children."); WriteLine($"{harry.Name}'s first child is named \"{harry.Children[0].Name}\"."); WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "apple"; WriteLine($"GenericThing with a string: {gt2.Process("apple")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square(number2)}"); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); WriteLine(john.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; // safely do something with explicitAlice } Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // do something with aliceAsEmployee } try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } string email1 = "*****@*****.**"; string email2 = "ian&test.com"; WriteLine($"{email1} is a valid e-mail address: {StringExtensions.isValidEmail(email1)}"); WriteLine($"{email2} is a valid e-mail address: {StringExtensions.isValidEmail(email2)}"); WriteLine($"{email1} is a valid e-mail address: {email1.isValidEmail()}"); WriteLine($"{email2} is a valid e-mail address: {email2.isValidEmail()}"); }
static void Main(string[] args) { /* Ch05 Commented for clarity while working through Chapter 06 * var bob = new Person(); * bob.Name = "Bob Smith"; * bob.DateOfBirth = new DateTime(1965, 12, 22); * bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatusOfZeusAtOlympia; * var alice = new Person * { * Name = "Alice Jones", * DateOfBirth = new DateTime(1998, 3, 7) * }; * * WriteLine(format: "{0} was born on {1: dddd, d MMMM yyyy}", * arg0: bob.Name, * arg1: bob.DateOfBirth); * * WriteLine(format: "{0} was born on {1:dd MMM yy}", arg0: alice.Name, * arg1: alice.DateOfBirth); * WriteLine(format: "{0}'s favorite wonder is {1}. Its integer is {2}.", arg0: bob.Name, arg1: bob.FavoriteAncientWonder, arg2: (int)bob.FavoriteAncientWonder); * * bob.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus; * // Another option is to set the value by casting 18 to the enum type, but this is more difficult to read * // bob.BucketList = (WondersOfTheAncientWorld)18; * WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}"); * * bob.Children.Add(new Person { Name = "Alfred" }); * bob.Children.Add(new Person { Name = "Zoe" }); * WriteLine($"{bob.Name} has {bob.Children.Count} children:"); * for (int child = 0; child < bob.Children.Count; child++) * { * WriteLine($"{bob.Children[child].Name}"); * } * // as a bonus, use a foreach statement * foreach (var children in bob.Children) * { * WriteLine($"{children.Name}"); * } * * BankAccount.InterestRate = 0.012M; // store a shared value * var jonesAccount = new BankAccount(); * jonesAccount.AccountName = "Mrs. Jones"; * jonesAccount.Balance = 2400; * * WriteLine(format: "{0} earned {1:C} interest.", arg0: jonesAccount.AccountName, arg1: jonesAccount.Balance * BankAccount.InterestRate); * var gerrierAccount = new BankAccount(); * gerrierAccount.AccountName = "Ms. Gerrier"; * gerrierAccount.Balance = 98; * * WriteLine(format: "{0} earned {1:C} interest", arg0: gerrierAccount.AccountName, arg1: gerrierAccount.Balance * BankAccount.InterestRate); * WriteLine($"{bob.Name} is a {Person.Species}"); * WriteLine($"{bob.Name} was born on {bob.HomePlanet}"); * var blankPerson = new Person(); * WriteLine(format: * "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.", * arg0: blankPerson.Name, * arg1: blankPerson.HomePlanet, * arg2: blankPerson.Instantiated); * * var gunny = new Person("Gunny", "Mars"); * WriteLine(format: * "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.", * arg0: gunny.Name, * arg1: gunny.HomePlanet, * arg2: gunny.Instantiated); * * // methods * bob.WriteToConsole(); * WriteLine(bob.GetOrigin()); * * // using tuples * (string, int) fruit = bob.GetFruit(); * WriteLine($"{fruit.Item1}, {fruit.Item2} there are"); * * // named tuples * var fruitNamed = bob.GetNamedFruit(); * WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}."); * var thing1 = ("Neville", 4); * * // inferring tuple names * WriteLine($"{thing1.Item1} has {thing1.Item2} children."); * var thing2 = (bob.Name, bob.Children.Count); * WriteLine($"{thing2.Name} has {thing2.Count} children."); * * // deconstructed * (string fruitName, int fruitNumber) = bob.GetFruit(); * WriteLine($"Deconstructed: {fruitName}, {fruitNumber}"); * * // passing parameters to methods + overloading methods * WriteLine(bob.SayHello()); * WriteLine(bob.SayHello("Emily")); * * // optional parameters * WriteLine(bob.OptionalParameters()); * // inferred by position * WriteLine(bob.OptionalParameters("Jump!", 98.5)); * // select using named params * WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!")); * // use named parameters to skip over optional params * WriteLine(bob.OptionalParameters("Poke!", active: false)); * * // controlling how parameters are passed * int a = 10; * int b = 20; * int c = 30; * * WriteLine($"Before a = {a}, b = {b}, c = {c}"); * bob.PassingParameters(a, ref b, out c); * WriteLine($"After: a = {a}, {b} = b, c = {c}"); * int d = 10; * int e = 20; * WriteLine($"Before d = {d}, e = {e}, f doesn't exist yet!"); * // simplified C# 7.0 syntax for out parameter * bob.PassingParameters(d, ref e, out int f); * WriteLine($"After: d = {d}, e = {e}, f = {f}"); * var sam = new Person * { * Name = "Sam", * DateOfBirth = new DateTime(1972, 1, 27) * }; * WriteLine(sam.Origin); * WriteLine(sam.Greeting); * WriteLine(sam.Age); * sam.FavoriteIceCream = "Chocolate Fudge"; * WriteLine($"Sam's favorite ice-cream flavor is {sam.FavoriteIceCream}."); * sam.FavoritePrimaryColor = "Red"; * WriteLine($"Sam's favorite primary color is {sam.FavoritePrimaryColor}."); * * // indexers * sam.Children.Add(new Person { Name = "Charlie" }); * sam.Children.Add(new Person { Name = "Ella" }); * WriteLine($"Sam's first child is {sam.Children[0].Name}"); * WriteLine($"Sam's second child is {sam.Children[1].Name}"); * WriteLine($"Sam's first child is {sam[0].Name}"); * WriteLine($"Sam's second child is {sam[1].Name}"); ***END BLOCK COMMENT *** END BLOCK COMMENT */ var harry = new Person { Name = "Harry" }; var mary = new Person { Name = "Mary" }; var jill = new Person { Name = "Jill" }; // call instance method var baby1 = mary.ProcreateWith(harry); // call static method var baby2 = Person.Procreate(harry, jill); // call an operator var baby3 = harry * mary; WriteLine($"{harry.Name} has {harry.Children.Count} children."); WriteLine($"{mary.Name} has {mary.Children.Count} children."); WriteLine($"{jill.Name} has {jill.Children.Count} children"); WriteLine(format: "{0}'s first child is named \"{1}\".", arg0: harry.Name, arg1: harry.Children[0].Name); WriteLine($"5! is {Person.Factorial(5)}"); harry.Shout += Harry_Shout; // "By assigning a method, () would replace harry.Poke(); harry.Poke(); harry.Poke(); harry.Poke(); Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jimmy" }, new Person { Name = "Richard" }, new Person { Name = "Adam" }, }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's IComparable implementation to sort:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use PersonComparer's IComparer implementation to sort:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); } var t1 = new Thing(); t1.Data = 42; WriteLine($"Thing with an integer: {t1.Process(42)}"); var t2 = new Thing(); t2.Data = "apple"; WriteLine($"Thing with a string: {t2.Process("apple")}"); var gt1 = new GenericThing <int>(); gt1.Data = 42; WriteLine($"GenericThing with an integer: {gt1.Process(42)}"); var gt2 = new GenericThing <string>(); gt2.Data = "Apple"; WriteLine($"GenericThing with an string: {gt2.Process("Apple")}"); string number1 = "4"; WriteLine($"{number1} squared is {Squarer.Square<string>(number1)}"); byte number2 = 3; WriteLine($"{number2} squared is {Squarer.Square(number2)}"); var dv1 = new DisplacementVector(3, 5); var dv2 = new DisplacementVector(-2, 7); var dv3 = dv1 + dv2; WriteLine($"({dv1.X}, {dv1.Y}) + ({dv2.X}, {dv2.Y}) = ({dv3.X}, {dv3.Y})"); Employee john = new Employee { Name = "John Jones", DateOfBirth = new DateTime(1990, 7, 28) }; john.WriteToConsole(); john.EmployeeCode = "JJ001"; john.HireDate = new DateTime(2014, 11, 23); WriteLine($"{john.Name} was hired on {john.HireDate:dd/MM/yy}"); // Writes Packt.Shared.Employee WriteLine(john.ToString()); Employee aliceInEmployee = new Employee { Name = "Alice", EmployeeCode = "AA123" }; Person aliceInPerson = aliceInEmployee; aliceInEmployee.WriteToConsole(); aliceInPerson.WriteToConsole(); WriteLine(aliceInEmployee.ToString()); WriteLine(aliceInPerson.ToString()); // explicit casting // Employee explicitAlice = (Employee)aliceInPerson; if (aliceInPerson is Employee) { WriteLine($"{nameof(aliceInPerson)} IS an Employee"); Employee explicitAlice = (Employee)aliceInPerson; // safely do something with explicitAlice } Employee aliceAsEmployee = aliceInPerson as Employee; if (aliceAsEmployee != null) { WriteLine($"{nameof(aliceInPerson)} AS an Employee"); // do something with aliceAsEmployee } // Inheriting Exceptions try { john.TimeTravel(new DateTime(1999, 12, 31)); john.TimeTravel(new DateTime(1950, 12, 25)); } catch (PersonException ex) { WriteLine(ex.Message); } // Using Static methods to reuse functionality string email1 = "*****@*****.**"; string email2 = "ian&test.com"; /* * WriteLine( * "{0} is a valid e-mail address: {1}", * arg0: email1, * arg1: StringExtensions.IsValidEmail(email1)); * WriteLine( * "{0} is a valid e-mail address: {1}", * arg0: email2, * arg1: StringExtensions.IsValidEmail(email2)); */ // Using Extension Methods to reuse functionality WriteLine( "{0} is a valid e-mail address: {1}", arg0: email1, arg1: email1.IsValidEmail()); WriteLine( "{0} is a valid e-mail address: {1}", arg0: email2, arg1: email2.IsValidEmail()); }