예제 #1
0
        static void Main(string[] args)
        {
            //声明变量,初始化变化,输出变量信息。
            var bob = new Person();

            bob.Name        = "Bob smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            WriteLine(format: "{0} was born on {1: dddd, d MMMM yyyy}", arg0: bob.Name, arg1: bob.DateOfBirth);
            //新增bob变量的FavoriteAncientWonder的值。

            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });
            WriteLine($"{bob.Name} has {bob.Children.Count} children:");
            foreach (Person p1 in bob.Children)
            {
                WriteLine($"{p1.Name}");
            }
            // for (int child = 0; child < bob.Children.Count; child++)
            // {
            // WriteLine($" {bob.Children[child].Name}") ;
            // }

            //bob.FavoriteAncientWonder =  WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            bob.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            WriteLine($"{bob. Name}' s bucket list is {bob. BucketList}");

            //输出
            WriteLine(format: "{0}'s FavoriteAncientWonder is {1},It's integer is {2}.", arg0: bob.Name, arg1: bob.FavoriteAncientWonder, arg2: (int)WondersOfTheAncientWorld.StatueOfZeusAtOlympia);

            //新增alice变量
            var alice = new Person()
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1984, 7, 3)
            };

            WriteLine(format: "{0} was born on {1:dd MMM yy}", arg0: alice.Name, arg1: alice.DateOfBirth);
            BankAccount.InterestRate = 0.012M;


            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs jones";
            jonesAccount.Balance     = 2400M;
            WriteLine(format: "{0} earned {1:C} interest rate.", arg0: jonesAccount.AccountName, arg1: jonesAccount.Balance * BankAccount.InterestRate);

            var gerrierAccount = new  BankAccount();

            gerrierAccount.AccountName = "Mr gerrier";
            gerrierAccount.Balance     = 98M;
            WriteLine(format: "{0} earned {1:C} interest rate.", arg0: gerrierAccount.AccountName, arg1: gerrierAccount.Balance * BankAccount.InterestRate);

            WriteLine($"{bob.Name} is a {Person.Species}");
            WriteLine($"{bob.Name}  was born in {bob.HomePlanet}");

            var blankPerson = new Person();

            WriteLine(format: "{0} of {1} was create 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 create at {2:hh:mm:ss} on a {2:dddd}.", arg0: gunny.Name, arg1: gunny.HomePlanet, arg2: gunny.Instantiated);

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            (string Name, int Number)fruit = bob.GetFruit();
            (string Name, int Number)      = bob.GetFruit();

            WriteLine($"There are {fruit.Number} {fruit.Name}.");
            WriteLine($"Deconstructed: {Name},{Number}");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children. ");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children. ");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("jump", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.9, command: "Hide!"));
            WriteLine(bob.OptionalParameters("Poke!", active: true));

            int a = 10, b = 20, c = 30;

            WriteLine("a = {0},b = {1},c = {2},", a, b, c);
            bob.PassingParameters(a, ref b, out c);
            WriteLine("a = {0},b = {1},c = {2},", a, b, c);

            int d = 10, e = 20;

            WriteLine($"Before: d = {d}, e = {e}, f doesn' t exist yet! ");
            // simplified C# 7. 0 syntax for the 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}. ");

            test t1 = new test();

            t1.setProperty("test");
            WriteLine(t1.getTest());

            //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}");
        }
예제 #2
0
        static void Main(string[] args)
        {
            var edixon = new Person();

            edixon.Name        = "Edixon van Vliet";
            edixon.DateOfBirth = new DateTime(1996, 3, 27);

            WriteLine(
                "{0} was born on {1:dddd, d MMMM yyyy}",
                edixon.Name,
                edixon.DateOfBirth
                );

            edixon.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;

            WriteLine(
                "{0}'s favorite wonder is {1}. It's integer is {2}.",
                edixon.Name,
                edixon.FavoriteAncientWonder,
                (int)edixon.FavoriteAncientWonder
                );

            edixon.BucketList =
                WondersOfTheAncientWorld.HangingGardensOfBabylon
                | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;

            WriteLine($"{edixon.Name}'s bucket list is {edixon.BucketList}");

            edixon.Children.Add(new Person {
                Name = "Alfred"
            });
            edixon.Children.Add(new Person {
                Name = "Zoe"
            });

            WriteLine($"{edixon.Name} has {edixon.Children.Count} children:");

            foreach (Person child in edixon.Children)
            {
                WriteLine($"  {child.Name}");
            }

            BankAccount.InterestRate = 0.012m;

            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs. Jones";
            jonesAccount.Balance     = 2400m;

            WriteLine(
                "{0} earned {1:c} interest.",
                jonesAccount.AccountName,
                jonesAccount.Balance * BankAccount.InterestRate
                );

            var gerrierAccount = new BankAccount();

            gerrierAccount.AccountName = "Ms. Gerrier";
            gerrierAccount.Balance     = 98m;

            WriteLine(
                "{0} earned {1:c} interest.",
                gerrierAccount.AccountName,
                gerrierAccount.Balance * BankAccount.InterestRate
                );

            WriteLine($"{edixon.Name} is a {Person.Species}");

            WriteLine($"{edixon.Name} was born on {edixon.HomePlanet}");

            var blankPerson = new Person();

            WriteLine(format:
                      "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.",
                      blankPerson.Name,
                      blankPerson.HomePlanet,
                      blankPerson.Instantiated
                      );

            var gunny = new Person("Gunny", "Mars");

            WriteLine(
                "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.",
                gunny.Name,
                gunny.HomePlanet,
                gunny.Instantiated
                );

            edixon.WriteToConsole();
            WriteLine(edixon.GetOrigin());

            (string, int)fruit = edixon.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var fruitNamed = edixon.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            var thing2 = (edixon.Name, edixon.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            (string fruitName, int fruitNumber) = edixon.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            WriteLine(edixon.SayHello());
            WriteLine(edixon.SayHello("Emily"));

            WriteLine(edixon.OptionalParameters());

            WriteLine(edixon.OptionalParameters("Jump!", 98.5));

            WriteLine(edixon.OptionalParameters(number: 52.7, command: "Hide!"));

            WriteLine(edixon.OptionalParameters("Poke!", active: false));

            int a = 10;
            int b = 20;
            int c = 30;

            WriteLine($"Before: a = {a}, b = {b}, c = {c}");

            edixon.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 the out parameter
            edixon.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.Name}'s favorite ice-cream flavor is {sam.FavoriteIceCream}."
                );

            sam.FavoritePrimaryColor = "Red";

            WriteLine(
                $"{sam.Name}'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}");
        }
예제 #3
0
        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()}");
        }
예제 #4
0
        static void Main(string[] args)
        {
            var bob = new Person();

            // WriteLine(bob.ToString());
            bob.Name                  = "Bob Smith";
            bob.DateOfBirth           = new DateTime(1965, 12, 22);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeus;
            bob.BucketList            = WondersOfTheAncientWorld.Pyramid
                                        | WondersOfTheAncientWorld.StatueOfZeus;
            // bob.BucketList = (WondersOfTheAncientWorld)5;
            bob.Children.Add(new Person {
                Name = "Jeff"
            });
            bob.Children.Add(new Person {
                Name = "Mary"
            });
            WriteLine($"{bob.Name} was bon on {bob.DateOfBirth:d}");
            WriteLine($"{bob.Name} favorite place is {(int)bob.FavoriteAncientWonder}");
            WriteLine($"{bob.Name} bucketlist is {bob.BucketList}");
            WriteLine($"{bob.Name} has {bob.Children.Count} children");
            for (int child = 0; child < bob.Children.Count; child++)
            {
                WriteLine(bob.Children[child].Name);
            }
            WriteLine($"{bob.Name} is a {Person.Species}");
            WriteLine($"{bob.Name} was born in {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
                );

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"{fruitNamed.Name}, {fruitNamed.Number} there are.");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("emily"));
            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("jump", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide"));
            WriteLine(bob.OptionalParameters("Poke", active: false));

            int a = 10, b = 20, 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}");
            a = 10; b = 20;
            WriteLine($"Before: a = {a}, b = {b}, d dose not exist");
            bob.PassingParameters(a, ref b, out int d);
            WriteLine($"After: a = {a}, b = {b}, d = {d}");

            BankAccount.IntrestRate = 0.012M;
            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.IntrestRate);

            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";
            sam.FavoritePrimaryColor = "red";
            WriteLine($"sam's Favorite icecream is {sam.FavoriteIceCream}");
            WriteLine($"sam's Favorite color is {sam.FavoritePrimaryColor}");
        }
예제 #5
0
        static void Main(string[] args)
        {
            var blankPerson = new Person("Anonymous", "Somewhere");

            WriteLine($"{blankPerson.Name} was created at {blankPerson.Instantiated}");

            int a = 10;
            int b = 20;
            int c = 30;

            var bob = new Person("Bob", "Earth");

            bob.Name        = "Bob";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            bob.BucketList  = WondersOfTheAncientWorld.HangingGardensOfBabylon
                              | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            var meaningOfLife = new Processor();

            (string Name, int Number)answer = meaningOfLife.GetTheData();

            WriteLine($"{answer.Name} -> {answer.Number}");
            WriteLine($"Before: a = {a}, b = {b}, c = {c}");
            bob.PassingParameters(a, ref b, out c);
            WriteLine($"After: a = {a}, b = {b}, c = {c}");

            var sam = new Person("Sam", Convert.ToString(new DateTime(1972, 1, 27)));

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);


            // BankAccount.InterestRate = 0.012m;

            // var jonesAccount = new BankAccount();
            // jonesAccount.AccountName = "Mrs. Johnes";
            // jonesAccount.Balance = 2400;

            // WriteLine($"{bob.Name} is {Person.Species} was born on {bob.PlanetOfBorn}");

            // 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);

            // bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            // bob.BucketList = (WondersOfTheAncientWorld)18;
            // WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}");

            // WriteLine(
            //     format: "{0} was born on {1:dddd, d MMMM yyyy}",
            //     arg0: bob.Name,
            //     arg1: bob.DateOfBirth
            // );

            // WriteLine(
            //     format: "{0}'s favorite wonder is {1}. It's integer is {2}",
            //     arg0: bob.Name,
            //     arg1: bob.FavoriteAncientWonder,
            //     arg2: (int)bob.FavoriteAncientWonder
            // );

            // bob.Children.Add(new Person {Name = "Alfred"});
            // bob.Children.Add(new Person {Name = "Zoe"});

            // WriteLine($"{bob.Name} has {bob.Children.Count} children: ");
            // foreach (Person child in bob.Children)
            // {
            //     WriteLine($"{child.Name}");
            // }
        }
예제 #6
0
        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());
        }
예제 #7
0
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            WriteLine($"{bob.Name} was born on {bob.DateOfBirth:dddd, d MMMM yyyy}");

            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            WriteLine($"{bob.Name}'s favorite wonder is {bob.FavoriteAncientWonder}. Its integer is {(int)bob.FavoriteAncientWonder}.");

            bob.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon
                             | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;

            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:");
            foreach (Person child in bob.Children)
            {
                WriteLine($"    {child.Name}");
            }

            WriteLine($"{bob.Name} is of species {Person.Species}");
            WriteLine($"{bob.Name} was born on planet {bob.HomePlanet}");

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());
            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");
            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}.");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            var alice = new Person
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine($"{alice.Name} was born on {alice.DateOfBirth:dd MMM yy}");

            BankAccount.InterestRate = 0.012M;
            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs. Jones";
            jonesAccount.Balance     = 2400;
            WriteLine($"{jonesAccount.AccountName} earned {jonesAccount.Balance * BankAccount.InterestRate:C} interest.");

            var gerrierAccount = new BankAccount();

            gerrierAccount.AccountName = "Ms. Gerrier";
            gerrierAccount.Balance     = 98;
            WriteLine($"{gerrierAccount.AccountName} earned {gerrierAccount.Balance * BankAccount.InterestRate:C}");

            var blankPerson = new Person();

            WriteLine($"{blankPerson.Name} of {blankPerson.HomePlanet} was created at {blankPerson.Instantiated:hh:mm:ss} on a {blankPerson.Instantiated:dddd}");

            var gunny = new Person("Gunny", "Mars");

            WriteLine($"{gunny.Name} of {gunny.HomePlanet} was created at {gunny.Instantiated:hh:mm:ss} on a {gunny.Instantiated:dddd}");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));
            WriteLine(bob.OptionalParameters("Poke", active: false));

            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!");
            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 = "Chocolage 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[0].Name}");
            WriteLine($"Sam's first child is {sam[0].Name}");
            WriteLine($"Sam's second child is {sam[1].Name}");
        }
예제 #8
0
        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);

            // call 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(new string('-', 50));
            WriteLine($"5! is {Person.Factorial(5)}");

            // delegates
            WriteLine(new string('-', 50));
            var p1     = new Person();
            int answer = p1.MethodIWantToCall("Frog");

            WriteLine(answer);

            var d       = new DelegateWithMatchingSignature(p1.MethodIWantToCall);
            int answer2 = d("Frog");

            WriteLine(answer2);

            WriteLine(new string('-', 50));
            harry.Shout += Harry_Shout;
            harry.Poke();
            harry.Poke();
            harry.Poke();
            harry.Poke();

            WriteLine(new string('-', 50));
            Person[] people =
            {
                new Person {
                    Name = "Simon"
                },
                new Person {
                    Name = "Jenny"
                },
                new Person {
                    Name = "Adam"
                },
                new Person {
                    Name = "Richard"
                }
            };

            WriteLine("Initial list for 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}");
            }

            WriteLine(new string('-', 50));

            var t = new Thing();

            t.Data = 42;
            WriteLine($"Thing : {t.Process("42")}");

            // generic
            var gt = new GenericThing <int>();

            gt.Data = 42;
            WriteLine($"Generic thing: {gt.Process("42")}");

            WriteLine(new string('-', 50));
            Employee e1 = new Employee
            {
                Name     = "John Jones",
                HireDate = new DateTime(1990, 7, 28)
            };

            e1.WriteToConsole();

            WriteLine(new string('-', 50));
            WriteLine(e1.ToString());


            WriteLine(new string('-', 50));
            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;
            }

            Employee e3 = aliceInPerson as Employee;

            if (e3 != null)
            {
                WriteLine($"{nameof(aliceInPerson)} IS an Employee");
            }

            WriteLine(new string('-', 50));
            try
            {
                e1.TimeTravel(new DateTime(1999, 12, 31));
                e1.TimeTravel(new DateTime(1950, 12, 25));
            }
            catch (PersonException ex)
            {
                WriteLine(ex.Message);
            }
            WriteLine(new string('-', 50));
            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()}");
        }
예제 #9
0
        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());
        }
예제 #10
0
        static void Main(string[] args)
        {
            // var person1 = new Person();
            // person1.Name = "Juliani";
            // person1.DateOfBirth = new System.DateTime(1995, 12, 12);
            // person1.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            // person1.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon |WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            // WriteLine($"{person1.Name} was born on {person1.DateOfBirth :dddd, d MMMM yyyy} and {person1.Name}'s favorite wonder is {person1.FavoriteAncientWonder}");
            // // p1.BucketList = (WondersOfTheAncientWorld)18;
            // WriteLine($"{person1.Name}'s bucket list is {person1.BucketList}");

            var person2 = new Person {
                Name        = "Janete",
                DateOfBirth = new DateTime(1977, 8, 19)
            };

            WriteLine($"{person2.Name} was born on {person2.DateOfBirth :d MMM yy} and is a {Person.Species} from {person2.HomePlanet}");

            person2.Children.Add(new Person {
                Name = "Juliani"
            });
            person2.Children.Add(new Person {
                Name = "Julia"
            });
            WriteLine(
                $"{person2.Name} has {person2.Children.Count} children:");
            for (int child = 0; child < person2.Children.Count; child++)
            {
                WriteLine($" {person2.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.");


            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}");

            p4.WriteToConsole();
            WriteLine(p4.GetOrigin());

            Tuple <string, int> fruit4 = p4.GetFruitCS4();

            WriteLine($"There are {fruit4.Item2} {fruit4.Item1}.");
            (string, int)fruit7 = p4.GetFruitCS7();
            WriteLine($"{fruit7.Item1}, {fruit7.Item2} there are.");

            var fruitNamed = p4.GetNamedFruit();

            WriteLine($"Are there {fruitNamed.Number} {fruitNamed.Name}?");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");
            var thing2 = (person2.Name, person2.Children.Count);

            WriteLine($"{thing2.Item1} has {thing2.Item2} children.");

            (string fruitName, int fruitNumber) = person2.GetFruitCS7();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            WriteLine(person2.SayHello());
            WriteLine(person2.SayHelloTo("Emily"));

            int a = 10;
            int b = 20;
            int c = 30;

            WriteLine($"Before: a = {a}, b = {b}, c = {c}");
            person2.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!");
            person2.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);
        }
예제 #11
0
        static void Main(string[] args)
        {
            Clear();

            WriteLine("-- People App --");

            var bob = new Person();

            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1956, 8, 24);

            WriteLine($"{bob.Name} was born on " +
                      $"{bob.DateOfBirth:dddd, d MMMM yyyy}");

            WriteLine($"{bob.Name} was born on {bob.HomePlanet}");

            WriteLine($"{bob.Name} is a {Person.Species}");

            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Jessica"
            });

            for (int child = 0; child < bob.Children.Count; child++)
            {
                WriteLine($"{bob.Children[child].Name} is Bob's Child.");
            }


            BankAccount.InterestRate = 0.012M;          // Store a shared value

            var alfredAccount = new BankAccount();      // Instance BankAccount

            alfredAccount.AccountName = "Mrs. Alfred";
            alfredAccount.Balance     = 2400;

            WriteLine(format: "{0} earned {1:C} interest.",
                      arg0: alfredAccount.AccountName,
                      arg1: alfredAccount.Balance * BankAccount.InterestRate);

            var jessicaAccount = new BankAccount();     // Instance BankAccount

            jessicaAccount.AccountName = "Ms. Jessica";
            jessicaAccount.Balance     = 5600;

            WriteLine(format: "{0} earned {1:C} interest.",
                      arg0: jessicaAccount.AccountName,
                      arg1: jessicaAccount.Balance * BankAccount.InterestRate);


            // Blank Person for Constructor
            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);

            // Defauls
            var thingOfDefault = new ThingOfDefaults();

            WriteLine("Default Values");
            WriteLine($"{thingOfDefault.Population} - {thingOfDefault.When} - " +
                      $"{thingOfDefault.Name} - {thingOfDefault.People}");


            // METHOD CALL
            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            WriteLine(new string('-', 35));

            // Return Value
            var toReturn = new Processor();
            var result   = toReturn.GetTheData();

            WriteLine(result.Text);
            WriteLine(result.Number);

            WriteLine(new string('-', 35));

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            WriteLine(new string('-', 35));

            var thing1 = ("Neville", 4);
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"ThingOne = {thing1.Item1} has {thing1.Item2} children.");
            WriteLine($"ThingTwo = {thing2.Name} has {thing2.Count} children.");

            WriteLine(new string('-', 35));

            (string name, int age)deconstruct = bob.GetPerson();
            WriteLine($"{deconstruct.name} is {deconstruct.age} yeas old!");

            WriteLine(new string('-', 35));
            WriteLine(bob.SayHello("Deve"));
            WriteLine(bob.SayHelloTo("Firat"));
            WriteLine(gunny.DirtyTalk("Zombi"));
            WriteLine(gunny.SaySomething("Blah Blash!"));

            WriteLine();

            WriteLine(new string('-', 35));
            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}");

            WriteLine();

            WriteLine(new string('-', 35));
            var sam = new Person
            {
                Name        = "Sam",
                DateOfBirth = new DateTime(1972, 1, 27)
            };

            sam.FavoriteIceCream     = "Chocolate Fudge";
            sam.FavoritePrimaryColor = "Red";

            WriteLine($"Sam's favorite ice-cream flavor is {sam.FavoriteIceCream}");
            WriteLine($"Sam's favorite primary color is {sam.FavoritePrimaryColor}");

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine($"Sam {sam.Age} yeas old!");

            WriteLine();

            WriteLine(new string('-', 35));
            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}");

            WriteLine();

            WriteLine(new string('-', 35));
            // -----------------------------------------------------------------
            object[] passengers =
            {
                new FirstClassPassenger {
                    AirMiles = 1_419
                },
예제 #12
0
        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());
        }
예제 #13
0
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            bob.BucketList  =
                WondersOfTheAncientWorld.HangingGardensOfBabylon
                |
                WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });
            bob.WriteToConsole();


            var alice = new Person
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            alice.WriteToConsole();

            BankAccount.InterestRate = 0.012M; // store a shared value
            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs. Jones";
            jonesAccount.Balance     = 2400;

            var gerrierAccount = new BankAccount();

            gerrierAccount.AccountName = "Mr. Gerrier";
            gerrierAccount.Balance     = 98;

            var blankPerson = new Person();

            WriteLine(
                format: "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}",
                blankPerson.Name,
                blankPerson.HomePlanet,
                blankPerson.Instantiated
                );

            var gunny = new Person("Gunny", "Mars");

            WriteLine(
                format: "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.",
                gunny.Name,
                gunny.HomePlanet,
                gunny.Instantiated
                );

            var fruit = bob.GetFruit();

            WriteLine($"{fruit.Name}, {fruit.Number} there are.");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1}, {thing1.Item2} there are.");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name}, {thing2.Count} there are.");

            // // store return value in a typle variable with two fields
            // (string name, int age) tupleWithNamedFields = GetPerson();
            // // typleWithNamedFields.name
            // // typleWithNamedFields.age

            // // deconstruct return value into two separate variables
            // (string name, int age) = GetPerson();
            // // name
            // // age

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"deconstructed: {fruitName}, {fruitNumber}");

            // command is Run!, number is 0, active is True
            WriteLine(bob.OptionalParameters());

            // command is jump!, number is 98.5, active is True
            WriteLine(bob.OptionalParameters("Jump!", 98.5));

            // command is Hide!, number is 52.7, active is True

            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));

            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}");

            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}");
        }
예제 #14
0
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            bob.BucketList  = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            WriteLine(
                format: "{0} was born on {1:dddd, d MMMM yyyy}",
                arg0: bob.Name,
                arg1: bob.DateOfBirth);

            /*
             * WriteLine(format:
             *  "{0}'s favorite wonder is {1}. It's integer is {2}.",
             *  arg0: bob.Name,
             *  arg1: bob.FavoriteAncientWonder,
             *  arg2: (int)bob.FavoriteAncientWonder);
             */

            //Bob Smith's bucket list is HangingGardensOfBabylon, MausoleumAtHalicarnassus
            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}");
            }


            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);


            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}.");


            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            // store return value in a tuple variable with two fields
            // (string name, int age) tupleWithNamedFields = GetPerson();
            // tupleWithNamedFields.name
            // tupleWithNamedFields.age
            // deconstruct return value into two separate variables
            // (string name, int age) = GetPerson();
            // name
            // age

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump!", 98.5));
            WriteLine(bob.OptionalParameters(
                          number: 52.7, command: "Hide!"));
            WriteLine(bob.OptionalParameters("Poke!", active: false));



            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 the 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}.");



            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}");
        }
        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)
                );
        }
예제 #16
0
        static void Main(string [] args)
        {
            var p1 = new Person();

            p1.Name        = "Bob Smith";
            p1.DateOfBirth = new System.DateTime(1965, 12, 22);
            p1.BucketList  = WondersOfTheAncientWorld.HangingGardensOfBabylon |
                             WondersOfTheAncientWorld.TempleOfArtemisAtEphesus;
            //WriteLine ( $"{p1.Name} was born on {p1.DateOfBirth: dddd, d MMMM yyyy}" );
            WriteLine($"{p1.Name}'s favourite wonder is {p1.BucketList}");
            WriteLine($"{p1.Name} is a {Person.Species}.");
            //WriteLine($"{p1.Name} was born on {p1.HomePlanet}");
            p1.WriteToConsole();
            WriteLine(p1.GetOrigin());
            WriteLine(p1.SayHello());
            WriteLine(p1.SayHello("Emily"));
            WriteLine(p1.OptionalParameters("Jump!", 98.5));

            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}");
            // }
            foreach (var child in p1.Children)
            {
                WriteLine($"  {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.");

            var p3 = new Person();

            WriteLine($"{p3.Name} was instantiated at {p3.Instantiated:h:mm:ss tt zz} on {p3.Instantiated:D}");

            var p4 = new Person("Aziz");

            WriteLine($"{p4.Name} was instantiated at {p4.Instantiated:h:mm:ss tt} on {p4.Instantiated:D}");

            // Tuples
            WriteLine("\nUsing Tuples...");
            Tuple <string, int> fruit4 = p1.GetFruitCS4();

            WriteLine($"There are {fruit4.Item1} {fruit4.Item2}.");

            // (string, int) fruit7 = p1.GetFruitCS7 ();
            // WriteLine($"{fruit7.Name}, {fruit7.Number} there are.");
            var fruitNamed = p1.GetNamedFruit();

            WriteLine($"Are there {fruitNamed.Number} {fruitNamed.Name}?");

            // Tuple name inference
            WriteLine("\nUsing Tuple name inferencing...");
            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.");

            // Deconstructing a Tuple for its individual values.
            WriteLine("\nDeconstructing a tuple...");
            (string fruitName, int fruitNumber) = p1.GetFruitCS7();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            // Passing parameters into functions
            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}");
            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.FavouriteIceCream = "Chocolate Fudge";
            WriteLine($"Sam's favourite ice-cream flavor is {sam.FavouriteIceCream}.");
            sam.FavouritePrimaryColor = "Red";
            WriteLine($"Sam's favourite primary color is {sam.FavouritePrimaryColor}.");

            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}");
        }
예제 #17
0
        static void Main(string[] args)
        {
            Person bob = new Person();

            bob.Name                  = "Bob Smith";
            bob.DateOfBirth           = new DateTime(1965, 12, 2);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            WriteLine(format: "{0} was born on {1:dddd, dd MMMM yyyy}",
                      arg0: bob.Name,
                      arg1: bob.DateOfBirth);
            WriteLine(format: "{0}'s favorite wonder is {1}. Its byte is {2}.",
                      arg0: bob.Name,
                      arg1: bob.FavoriteAncientWonder,
                      arg2: (byte)bob.FavoriteAncientWonder);
            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });
            WriteLine($"{bob.Name} has {bob.Children.Count} children:");
            foreach (Person child in bob.Children)
            {
                WriteLine($"\t- {child.Name}");
            }
            WriteLine($"{bob.Name} is a {Person.Species}.");
            WriteLine($"{bob.Name} was born on {bob.HomePlanet}.");
            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());
            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");
            (string Name, int Number)namedFruit = bob.GetNamedFruit();
            WriteLine($"There are {namedFruit.Number} {namedFruit.Name}.");
            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName} and {fruitNumber}.");
            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));
            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump!", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));
            WriteLine(bob.OptionalParameters(command: "Poke!", active: false));

            Person alice = new Person
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine(format: "{0} was born on {1:dd MMM yy}",
                      arg0: alice.Name,
                      arg1: alice.DateOfBirth);

            BankAccount.InterestRate = 0.012M;
            BankAccount 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);
            BankAccount 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);

            Person 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
                      );

            Person 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
                      );

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            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 does not exist yet.");
            bob.PassingParameters(d, ref e, out int f);
            WriteLine($"After: d = {d}, e = {e}, f = {f}.");

            Person 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.Name}'s favorite ice-cream flavor is {sam.FavoriteIceCream}.");
            sam.FavoritePrimaryColor = "Red";
            WriteLine($"{sam.Name}'s favorite primary color is {sam.FavoritePrimaryColor}.");
            sam.Children.Add(new Person {
                Name = "Charlie"
            });
            sam.Children.Add(new Person {
                Name = "Ella"
            });
            WriteLine($"{sam.Name}'s first child is {sam.Children[0].Name}.");
            WriteLine($"{sam.Name}'s second child is {sam.Children[1].Name}.");
            WriteLine($"{sam.Name}'s first child is {sam[0].Name}.");
            WriteLine($"{sam.Name}'s second child is {sam[1].Name}.");

            object [] passengers =
            {
                new FirstClassPassenger {
                    AirMiles = 1_419
                },
예제 #18
0
        static void Main(string[] args)
        {
            var john = new Person("John", "Earth");

            john.Name        = "John Doe";
            john.DateOfBirth = new DateTime(1992, 6, 19);

            WriteLine(format: "{0} was born on {1:dddd, d MMMM yyyy}", // dddd: name of day, d: number of day, MMMM: name of month, yyyy: full year
                      arg0: john.Name,
                      arg1: john.DateOfBirth);

            WriteLine(format: "{0} was born on {1:dd MMM yy}",
                      arg0: john.Name,
                      arg1: john.DateOfBirth);
            WriteLine();

            // ==========Enums==========
            // Using enums in PacktLibrary WondersOfTheAncientWorld.cs
            john.FavoriteWonder = WondersOfTheAncientWorld.HangingGardensOfBabylon;
            WriteLine(format: "{0}'s favorite wonder is {1}. It's integer is {2}",
                      arg0: john.Name,
                      arg1: john.FavoriteWonder,
                      arg2: (int)john.FavoriteWonder); // enum valuesa are initialy stored as an int for efficiency.

            // enums can also be called and set using int values when useing the decoration [System.Flags] and inheriting from byte
            john.BucketList = WondersOfTheAncientWorld.ColossusOfRhodes | WondersOfTheAncientWorld.GreatPyramidOfGiza;
            WriteLine($"{john.Name}'s bucket list is {john.BucketList}");
            john.BucketList = (WondersOfTheAncientWorld)33;
            WriteLine($"{john.Name}'s bucket list is {john.BucketList}");
            WriteLine();

            // ==========Objects with Lists==========
            // calling from the public List<Person> in PacktLibrary Person.cs
            john.Children.Add(new Person("Jane", john.HomePlanet));
            john.Children.Add(new Person("Jack", john.HomePlanet));
            WriteLine($"{john.Name} has {john.Children.Count} children:");
            for (int child = 0; child < john.Children.Count; child++)
            {
                WriteLine($"    {john.Children[child].Name}");
            }
            WriteLine();

            // ==========Using static values==========
            // using BankAccount.cs class
            BankAccount.InterestRate = 0.12M; // store a shared value, InterestRate is static

            var doeAccount = new BankAccount();

            doeAccount.AccountName = "Mr. Doe";
            doeAccount.Balance     = 43_600;

            WriteLine(format: "{0} earned {1:C} interest.", // :C - currency format
                      arg0: doeAccount.AccountName,
                      arg1: doeAccount.Balance * BankAccount.InterestRate);

            var smithAccount = new BankAccount();

            smithAccount.AccountName = "Mr. Smith";
            smithAccount.Balance     = 1_400;

            WriteLine(format: "{0} earned {1:C} interest.", // :C - currency format
                      arg0: smithAccount.AccountName,
                      arg1: smithAccount.Balance * BankAccount.InterestRate);

            // using const value from Person.cs
            WriteLine($"{john.Name} is a {Person.Species}. (We hope)");

            // using readonly value from Person.cs
            WriteLine($"{john.Name} is from {john.HomePlanet}. (If he is a H**o Sapien)");
            WriteLine();


            // ==========Contrcutors==========
            // Contrcutors with arguments
            // using PersonArgs.cs
            var mike = new Person("Mike", "Mars");

            WriteLine(format: "{0} of {1} was created at {2:hh:mm:ss} on a {2:dddd}.",
                      arg0: mike.Name,
                      arg1: mike.HomePlanet,
                      arg2: mike.Instantiated);

            // using methods
            mike.WriteToConsole();
            WriteLine(mike.GetOrigin());
            WriteLine();

            // ==========Tuples==========
            // using tuples
            (string, int)fruit = mike.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var fruitNamed = mike.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}.");

            // variable use of tuples
            var thing1 = ("George", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} Children.");

            var thing2 = (john.Name, john.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            // Deconstructing tuples
            (string fruitName, int fruitNumber) = mike.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");
            // taking the values held in GetFruit() and assigning the tuple to the new variables
            WriteLine();


            // ==========Param Methods and Overloading==========
            WriteLine(mike.SayHello());
            WriteLine(mike.SayHello("John"));
            WriteLine();

            // ==========Optional Parameters==========
            WriteLine(mike.OptionalParameters());              // will output default values in PersonArgs.cs
            WriteLine(mike.OptionalParameters("Jump!", 98.5)); // overwrites the default values

            // delcaring some parameters can be skipped if you name the parameters based on the method
            WriteLine(mike.OptionalParameters(number: 29.1, command: "Hide!")); // parameter calues can be named when declaring them
            WriteLine(mike.OptionalParameters("Walk!", active: false));
            WriteLine();

            // ==========Controlling How Parameters are Passed==========
            // by value (default)(in), ref(in-out), and as an out parameter(out)
            int a = 10;
            int b = 20;
            int c = 30;

            WriteLine($"Before: a = {a}, b = {b}, c = {c}.");
            mike.PassingParameters(a, ref b, out c);
            WriteLine($"After: a = {a}, b = {b}, c = {c}.");
            // When passing a value as a parameter by default, the current VALUE
            // is passed, not the variable itself. a before and after is 10.
            // When passing y as a reference to b, b increments as y increments.
            // When using an out, the value in z overwrites the value of c.

            // In C# 7.0 we can simpify code that uses the out variable:
            int d = 10;
            int e = 20;

            WriteLine($"Before: d = {d}, e = {e}, f doesn't exist yet!");
            // simplified syntax for the out parameter
            mike.PassingParameters(d, ref e, out int f);
            WriteLine($"After: d = {d}, e = {e}, f ={f}");
            WriteLine();

            // ==========Using Properties in C# 6+==========
            // Using PersonAutoGen.cs
            var sam = new Person
            {
                Name        = "Sam",
                DateOfBirth = new DateTime(1928, 1, 27)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);

            // settable properties
            sam.FavoriteIceCream = "Chocolate Fudge";
            WriteLine($"Sam's favorite ice cream is {sam.FavoriteIceCream}.");

            sam.FavoritePrimaryColor = "red";
            WriteLine($"Sam's favorite 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}");
        }
예제 #19
0
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name                  = "Bob Smith";
            bob.DateOfBirth           = new DateTime(1965, 12, 22);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            bob.BuckedList            = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });

            WriteLine(format: "{0} was born on {1:dddd, d MMMM yyyy}",
                      arg0: bob.Name,
                      arg1: bob.DateOfBirth);
            WriteLine(format: "{0}'s favorite wonder is {1}. Its integer is {2}",
                      arg0: bob.Name,
                      arg1: bob.FavoriteAncientWonder,
                      arg2: (int)bob.FavoriteAncientWonder);
            WriteLine($"{bob.Name}'s bucket list is {bob.BuckedList}");
            WriteLine($"{bob.Name} has {bob.Children.Count} children:");
            for (int child = 0; child < bob.Children.Count; child++)
            {
                WriteLine($"  {bob.Children[child].Name}");
            }

            BankAccount.InterestRate = 0.012M;

            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 = "Mrs. 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);

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children");

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump!", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));
            WriteLine(bob.OptionalParameters("Poke!", active: false));

            int a = 10;
            int b = 20;
            int c = 30;

            WriteLine($"Befire a = {a}, b = {b}, c = {c}");
            bob.PassingParameters(a, ref b, out c);
            WriteLine($"After: a = {a}, b = {b}, c = {c}");

            var sam = new Person {
                Name        = "Sam",
                DateOfBirth = new DateTime(1972, 1, 27)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);

            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}");

            object[] passengers =
            {
                new FirstClassPassenger {
                    AirMiles = 1_419
                },
예제 #20
0
파일: Program.cs 프로젝트: vladar21/Code
        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()}.");
        }
예제 #21
0
        static void Main(string[] args)
        {
            // bob
            var bob = new Person();

            bob.Name                   = "Bob Smith";
            bob.DateOfBirth            = new DateTime(1970, 11, 30);
            bob.FavouriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            bob.BucketList             = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            bob.Children.Add(new Person {
                Name = "Alf"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });
            WriteLine();
            WriteLine("Bob-----------------------------------------");
            WriteLine(bob.getOrigin());
            bob.WriteToConsole();
            WriteLine(
                format: "{0} was born on {1:dddd, d MMMM yyyy}",
                arg0: bob.Name,
                arg1: bob.DateOfBirth
                );
            WriteLine(
                format: "{0}'s favourite wonder is {1}, it's integer is {2}",
                arg0: bob.Name,
                arg1: bob.FavouriteAncientWonder,
                arg2: (int)bob.FavouriteAncientWonder
                );
            WriteLine($"{bob.Name}'s bucket list is: {bob.BucketList}");
            WriteLine($"{bob.Name} has {bob.Children.Count} children");
            foreach (Person child in bob.Children)
            {
                WriteLine($"child name: {child.Name}");
            }
            WriteLine($"{bob.Name} is a {Person.Species}");
            WriteLine($"{bob.Name} is from {bob.HomePlanet}");

            WriteLine();
            WriteLine("Tuples-----------------------------------------");
            (string, int)fruit = bob.GetFruit();
            WriteLine($"USING TUPLES: {fruit.Item1}, {fruit.Item2} there are.");
            var vegetablesNamed = bob.GetVeg();

            WriteLine($"USING named TUPLES: {vegetablesNamed.Name}, {vegetablesNamed.Number} there are.");

            // Deconstructing tuples
            (string name, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed TUPLE: {name}, {fruitNumber}");

            // Inferring tuple names
            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Item1} has {thing2.Item2} children-");

            // optional parameters
            WriteLine();
            WriteLine("Optional Parameters------------------------------");
            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump", 2.4));
            WriteLine(bob.OptionalParameters(number: 2.4, active: false));
            WriteLine(bob.OptionalParameters(active: false, command: "Fly"));
            WriteLine(bob.OptionalParameters("Walk", active: false));


            // alice
            var alice = new Person();

            alice.Name        = "Alice Smith";
            alice.DateOfBirth = new DateTime(1968, 10, 22);

            WriteLine();
            WriteLine("Alice------------------------------");
            WriteLine(
                format: "{0} was born on {1:dd, MMM yy}",
                arg0: alice.Name,
                arg1: alice.DateOfBirth
                );

            WriteLine();
            WriteLine("Constructors----------------------------");
            // blank Person to use constructor
            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
                );


            // bank account class use
            BankAccount.InterestRate = 0.012M;

            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs Jones";
            jonesAccount.Balance     = 2400;

            var smithAccount = new BankAccount();

            smithAccount.AccountName = "Mrs Smith";
            smithAccount.Balance     = 800;

            WriteLine();
            WriteLine("public STATIC property - shared across all instances of class - bank interest rate demonstrateS ---------------");
            WriteLine(
                format: "{0} earned {1:C} interest",
                arg0: jonesAccount,
                arg1: jonesAccount.Balance * BankAccount.InterestRate
                );
            WriteLine(
                format: "{0} earned {1:C} interest",
                arg0: smithAccount,
                arg1: smithAccount.Balance * BankAccount.InterestRate
                );


            WriteLine();
            WriteLine("PARAMETERS  - 3 ways: by value, reference or an an out parameter ---------------");
            int a = 10;
            int b = 20;
            int c = 30; // no point in setting value of c as gets repoaced from within the method

            bob.PassingParameters(a, ref b, out c);
            WriteLine($"a: {a}, b: {b}, c {c}");

            int d = 10;
            int e = 20;

            WriteLine($"d: {d}, e: {e}, f doesn't exist yet");
            bob.PassingParameters(d, ref e, out int f);
            WriteLine($"d: {d}, e: {e}, f: {f}");


            WriteLine();
            WriteLine("Partial classes and properties, and indexers ---------------");
            var sam = new Person
            {
                Name        = "Sam",
                DateOfBirth = new DateTime(1972, 1, 27)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);
            sam.FavouriteIceCream      = "Mint choc chip";
            sam.FavouritePrimaryColour = "Red";

            WriteLine($"{sam.Name}'s favourite ice cream is {sam.FavouriteIceCream} and fav primary colour is {sam.FavouritePrimaryColour}");
            sam.Children.Add(new Person {
                Name = "Charlie"
            });
            sam.Children.Add(new Person {
                Name = "Ella"
            });

            // if you had no indexer set up for Children:
            WriteLine($"{sam.Name}'s first child is {sam.Children[0].Name}");
            WriteLine($"{sam.Name}'s second- child is {sam.Children[1].Name}");

            // if you have indexer set up for Children - does it really add much value? I think it reduces ease of reading code...
            WriteLine($"{sam.Name}'s first child is {sam[0].Name}");
            WriteLine($"{sam.Name}'s second- child is {sam[1].Name}");
        }
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name                  = "Bob Smith";
            bob.DateOfBirth           = new DateTime(1954, 12, 22);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            bob.BucketList            = (WondersOfTheAncientWorld)18;
            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Suzie"
            });

            WriteLine(
                format: "{0} was born on {1:dddd, d MMMM yyyy}",
                arg0: bob.Name,
                arg1: bob.DateOfBirth
                );

            WriteLine(
                format: "{0}'s favorite wonder is {1}. It's integer is {2}.",
                arg0: bob.Name,
                arg1: bob.FavoriteAncientWonder,
                arg2: (int)bob.FavoriteAncientWonder
                );

            WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}");

            WriteLine($"Bob has {bob.Children.Count} children.");
            for (int child = 0; child < bob.Children.Count; child++)
            {
                WriteLine($"{bob.Children[child].Name}");
            }
            ;

            foreach (Person child in bob.Children)
            {
                WriteLine($"Saying hello to {child.Name}!");
            }
            ;

            WriteLine($"{bob.Name} is a {Person.Species}");
            WriteLine($"{bob.Name} was born on {bob.HomePlanet}");

            var alice = new Person
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine(
                format: "{0} was born on {1:dd MMM yy}",
                arg0: alice.Name,
                arg1: alice.DateOfBirth
                );

            // Bank Accounts
            BankAccount.InterestRate = 0.012M; // storing 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 leslieAccount = new BankAccount();

            leslieAccount.AccountName = "Mr. Alldridge";
            leslieAccount.Balance     = 100;

            WriteLine(format: "{0} earned {1:C} interest.",
                      arg0: leslieAccount.AccountName,
                      arg1: leslieAccount.Balance * BankAccount.InterestRate
                      );

            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
                );

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            var namedFruit = bob.GetNamedFruit();

            WriteLine($"{namedFruit.Name} and {namedFruit.Number} exist");

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children."); // infers Name and Count as the named fields

            // deconstructing tuples
            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed {fruitName}, {fruitNumber}");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Leslie"));

            WriteLine(bob.OptionalParams());
            WriteLine(bob.OptionalParams(command: "Jump", number: 99));
            WriteLine(bob.OptionalParams("Poke!", active: false));

            int a = 10;
            int b = 20;

            WriteLine($"Before: a = {a}, b = {b}, c = doesn't exist");

            bob.PassingParameters(a, ref b, out int c);

            WriteLine($"After: a = {a}, b = {b}, c = {c}");

            var sam = new Person
            {
                Name        = "Sam",
                DateOfBirth = new DateTime(1992, 6, 9)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);

            sam.FavouriteIceCream = "Chocolate Fudge";
            WriteLine($"Sam's favourite ice-cream flavour is {sam.FavouriteIceCream}.");

            sam.FavouritePrimaryColor = "Red";
            WriteLine($"Sam's favourite primary color is {sam.FavouritePrimaryColor}");

            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}");
        }
예제 #23
0
        static void Main(string[] args)
        {
            // Setting and outputting field values

            var bob = new Person();

            WriteLine(bob.ToString());
            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);

            WriteLine(
                format: "{0} was born on {1:dddd, d MMMM yyyy}",
                arg0: bob.Name,
                arg1: bob.DateOfBirth);

            var alice = new Person
            {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine(
                format: "{0} was born on {1:dd MMM yy}",
                arg0: alice.Name,
                arg1: alice.DateOfBirth);

            // Storing a value using an enum type

            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;

            WriteLine(format:
                      "{0}'s favorite wonder is {1}. It's integer is {2}.",
                      arg0: bob.Name,
                      arg1: bob.FavoriteAncientWonder,
                      arg2: (int)bob.FavoriteAncientWonder);

            // Storing multiple values using an enum type

            bob.BucketList =
                WondersOfTheAncientWorld.HangingGardensOfBabylon
                | WondersOfTheAncientWorld.MausoleumAtHalicarnassus
                | WondersOfTheAncientWorld.StatueOfZeusAtOlympia;

            // bob.BucketList = (WondersOfTheAncientWorld)18;

            WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}");

            // Storing multiple values using collections

            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}");
            }
            foreach (var chi in bob.Children)
            {
                WriteLine($"=>{chi.Name}");
            }

            // Making a field static

            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);

            BankAccount.InterestRate = 0.02M;
            WriteLine(format: "{0} earned {1:C} interest.(InterestRate changed)",
                      arg0: jonesAccount.AccountName,
                      arg1: jonesAccount.Balance * BankAccount.InterestRate);
            WriteLine(format: "{0} earned {1:C} interest.(InterestRate changed)",
                      arg0: gerrierAccount.AccountName,
                      arg1: gerrierAccount.Balance * BankAccount.InterestRate);

            // Making a field constant

            WriteLine($"{bob.Name} is a {Person.Species}");

            // Making a field read-only

            WriteLine($"{bob.Name} was born on {bob.HomePlanet}");

            // Initializing fields with constructors

            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);

            // Returning values from methods

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            // Combining multiple returned values using tuples

            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            // Naming the fields of a tuple

            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}.");

            // Inferring tuple names

            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            // Deconstructing tuples

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            // Defining and passing parameters to methods

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            // Passing optional parameters and naming arguments

            WriteLine(bob.OptionalParameters());

            WriteLine(bob.OptionalParameters("Jump!", 98.5));

            WriteLine(bob.OptionalParameters(
                          number: 52.7, command: "Hide!"));

            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 syntax for the out parameter
            bob.PassingParameters(d, ref e, out int f);

            WriteLine($"After: d = {d}, e = {e}, f = {f}");

            // Defining read-only properties

            var sam = new Person
            {
                Name        = "Sam",
                DateOfBirth = new DateTime(1972, 1, 27)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);

            // Defining settable properties

            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}.");

            // Defining 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}");
        }
예제 #24
0
        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());
        }
예제 #25
0
        static void Main(string[] args)
        {
            var bob = new Person();

            bob.Name        = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 22);
            WriteLine(format: "{0} was born on {1:dddd,d MMMM yyyy}",
                      arg0: bob.Name,
                      arg1: bob.DateOfBirth);

            //
            var alice = new Person {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine(format: "{0} was born on {1:dd MMM yy}",
                      arg0: alice.Name,
                      arg1: alice.DateOfBirth);

            bob.FavouriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            WriteLine(format: "{0}'s favourite wonder is {1}. Its interger is {2}.",
                      arg0: bob.Name,
                      arg1: bob.FavouriteAncientWonder,
                      arg2: (int)bob.FavouriteAncientWonder);

            //bob.BucketList = WondersOfTheAncientWorld.MausoleumAtHalicarnassus | WondersOfTheAncientWorld.HangingGardensOfBabylon;
            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}");
            }

            //Making a field static
            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
                      );

            //Making a field constant
            WriteLine($"{bob.Name} is a {Person.Species} and PI constant is {Math.PI}.");

            //Making a field Read-only
            WriteLine($"{bob.Name} was born on {bob.HomePlanet}.");

            //Initializing fields with constructors
            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);

            //Returnig values from methods
            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());

            //call tuple method
            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");

            //Naming fields of a tuple
            var fruitNamed = bob.GetFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}");

            //infering tuple names
            var things1 = ("Neville", 4);

            WriteLine($"{things1.Item1} has {things1.Item2} children");
            var thing2 = (bob.Name, bob.Children.Count);

            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            //Deconstructin tuples


            // deconstruct return value into two separate variables
            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");
            // fruitName
            // fruitNumber

            //Defining and Passing Parameters to methods
            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));

            //Passing Optional Parameters & Naming Arguments
            WriteLine(bob.OptionalParameters(number: 98.33, command: "Alright!"));

            //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}");

            //Access Control with Properties & Indexers
            var sam = new Person {
                Name = "Sam", DateOfBirth = new DateTime(1972, 1, 27)
            };

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);

            //Defining Settable Properties
            sam.FavouriteIceCream = "Chocolate Fudge";
            WriteLine($"Sam's favourite ice-cream floavor is {sam.FavouriteIceCream}.");
            sam.FavouritePrimaryColor = "GREen";
            WriteLine($"Sam's favourite primary color is {sam.FavouritePrimaryColor}");

            //Defining 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}");

            //Pattern matching with Objects
            object[] passengers =
            {
                new FirstClassPassenger {
                    AirMiles = 1_419
                },
 private static void DemoWriteMethod(Person p1)
 {
     // Exercise: Write a method
     p1.WriteToConsole();
     WriteLine(p1.GetOrigin());
 }
예제 #27
0
파일: Program.cs 프로젝트: vladar21/Code
        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 MMMM yy}");

            p1.FavouriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            WriteLine($"{p1.Name}'s favourite wonder is {p1.FavouriteAncientWonder}");

            p1.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon |
                            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}");

            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}?");

            // C# 7.0
            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");
            var thing2 = (p1.Name, p1.Children.Count);

            WriteLine($"{thing2.Item1} has {thing2.Item2} children.");

            // C# 7.1
            var thing3 = (p1.Name, p1.Children.Count);

            WriteLine($"{thing3.Name} has {thing3.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}");

            // упрощенный синтаксис параметров out в C# 7
            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}");
        }
예제 #28
0
        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()}.");
        }
예제 #29
0
        static void Main(string[] args)
        {
            //Bob is instantiated and then his fields are set later
            var bob = new Person();

            bob.Name                  = "Bob Smith";
            bob.DateOfBirth           = new DateTime(1965, 12, 22);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            bob.BucketList            = WondersOfTheAncientWorld.HangingGardensOfBabylon | WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
            // equivalent to bob.BucketList = (WondersOfTheAncientWorld)18 due to byte
            bob.Children.Add(new Person {
                Name = "Alfred"
            });
            bob.Children.Add(new Person {
                Name = "Zoe"
            });
            WriteLine(
                format: "{0} was born on {1:dddd, d MMMM yyyy}.",
                arg0: bob.Name,
                arg1: bob.DateOfBirth
                );
            WriteLine(
                format: "{0}'s favorite wonder is {1}. Its integer is {2}.",
                arg0: bob.Name,
                arg1: bob.FavoriteAncientWonder,
                arg2: (int)bob.FavoriteAncientWonder
                );
            WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}");
            WriteLine($"{bob.Name} has {bob.Children.Count} children:");
            //using a for loop to get the name of the children

/*             for (int child = 0; child < bob.Children.Count; child++) {
 *              WriteLine($" {bob.Children[child].Name}");
 *          } */
            //using a foreach loop to iterate through the list
            foreach (Person child in bob.Children)
            {
                WriteLine($" {child.Name}");
            }
            WriteLine($"{bob.Name} is a {Person.Species}");
            WriteLine($"{bob.Name} was born on {bob.HomePlanet}");


            //Alice is instantiated with the fields set at that time
            var alice = new Person {
                Name        = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };

            WriteLine(
                format: "{0} was born on {1:dd MMM yy}",
                arg0: alice.Name,
                arg1: alice.DateOfBirth
                );

            BankAccount.InterestRate = 0.012M; //store a shared value
            var jonesAccount = new BankAccount();

            jonesAccount.AccountName = "Mrs. Jones";
            jonesAccount.Balance     = 2400;
            decimal jonesInterest = jonesAccount.Balance * BankAccount.InterestRate;

            WriteLine($"{jonesAccount.AccountName} earned {jonesInterest:C} interest.");

            var gerrierAccount = new BankAccount();

            gerrierAccount.AccountName = "Ms. Gerrier";
            gerrierAccount.Balance     = 98;
            decimal gerrierInterest = (gerrierAccount.Balance * BankAccount.InterestRate);

            WriteLine($"{gerrierAccount.AccountName} earned {gerrierInterest:C} interest.");


            var blankPerson = new Person();

            WriteLine($"{blankPerson.Name} of {blankPerson.HomePlanet} was created at " +
                      $"{blankPerson.Instantiated:hh:mm:ss} on a {blankPerson.Instantiated:dddd}.");

            var gunny = new Person("Gunny", "Mars");

            WriteLine($"{gunny.Name} of {gunny.HomePlanet} was created at " +
                      $"{gunny.Instantiated:hh:mm:ss} on a {gunny.Instantiated:dddd}.");

            bob.WriteToConsole();
            WriteLine(bob.GetOrigin());
            //item syntax
            (string, int)fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");
            //named syntax
            var fruitNamed = bob.GetNamedFruit();

            WriteLine($"There are {fruitNamed.Number} {fruitNamed.Name}");
            //using the item1, item2 syntax
            var thing1 = ("Neville", 4);

            WriteLine($"{thing1.Item1} has {thing1.Item2} children.");

            //set these equal to the class fields
            var thing2 = (bob.Name, bob.Children.Count);

            //can reference it using those automatically
            WriteLine($"{thing2.Name} has {thing2.Count} children.");

            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");

            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Emily"));
            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump!", 98.5));
            WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));
            WriteLine(bob.OptionalParameters("Poke!", active: false));

            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 the 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}.");
            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}");
        }
예제 #30
0
파일: Program.cs 프로젝트: skomja00/Csharp
        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()
                );
        }