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

            // 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());
        }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Person bob = new Person();
            WriteLine(bob.ToString());
            bob.Name = "Bob Smith";
            bob.DateOfBirth = new DateTime(1965, 12, 2);
            bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
            WriteLine(
                format: "{0} was born on {1:dddd, dd/MM/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);

            bob.Children.Add(new Person());
            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}");
            }
            WriteLine($"{bob.Name}'s 1st child is {bob.Children[0].Name}");
            // indexer
            WriteLine($"{bob.Name}'s 1st child is {bob[0].Name}");
            // const field
            WriteLine(
                $"{bob.Name} is a {Person.Species}");
            // Add Friend
            bob.addFriend(new Person("Edward", "Earth"));
            bob.addFriend(new Person("Edwin", "Mars"));
            List<Person> allFriends = bob.getFriend();
            for(int idx=0; idx< allFriends.Count; idx++){
                WriteLine($"{bob.Name}'s friend {idx}: {allFriends[idx].Name}");
            }
            for(int idx=0; idx< allFriends.Count; idx++){
                string idxString = idx.ToString();
                WriteLine($"{bob.Name}'s friend {idx}: {bob[idxString].Name}");
            }
            // calling Method
            WriteLine("** WriteLine(bob.GetOrigin())");
            WriteLine(bob.GetOrigin());
            WriteLine("** bob.WriteToConsole()");
            bob.WriteToConsole();
            var fruit = bob.GetFruit();
            WriteLine($"{fruit.Item1}, {fruit.Item2} there are.");
            var fruitNamed = bob.GetNamedFruit();
            WriteLine($"{fruitNamed.Name}, {fruitNamed.Number} there are.");
            (string fruitName, int fruitNumber) = bob.GetFruit();
            WriteLine($"Deconstructed: {fruitName}, {fruitNumber}");
            (string fruitName, int fruitNumber) dcFruit = bob.GetFruit();
            WriteLine($"Deconstructed 2: {dcFruit.fruitName}, {dcFruit.fruitNumber}");
            WriteLine(bob.SayHello());
            WriteLine(bob.SayHello("Edward"));
            WriteLine(bob.OptionalParameters());
            WriteLine(bob.OptionalParameters("Jump!", 98.5));
            WriteLine(bob.OptionalParameters(command: "ALL!", active: false));
            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 alice = new Person
            {
                Name = "Alice Jones",
                DateOfBirth = new DateTime(1998, 3, 7)
            };
            WriteLine(
                format: "{0} was born on {1:dddd, dd/MM/yyyy}",
                arg0: alice.Name,
                arg1: alice.DateOfBirth);

            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(initialName:"Gunny", homePlanet:"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);
            // Things of Default
            var default1 = new ThingOfDefaults();
            WriteLine("** Thing of Default");
            WriteLine(
                format: "int: {0}, DateTime:{1}, string:{2}, {3},",
                default1.Population, default1.When,
                default1.Name, default1.People.Count
                );
            // ----------------------
            // BankAccount
            // ----------------------
            BankAccount.InterestRate = 0.012M; // store a shared value
            var jonesAccount = new BankAccount
                {
                    AccountName= "Mrs. Jones",
                    Balance= 2400
                };

            WriteLine(format: "{0}'s Balanace is {1:N} earned {2:C} interest.",
                arg0: jonesAccount.AccountName,
                arg1: jonesAccount.Balance,
                arg2: jonesAccount.Balance * BankAccount.InterestRate);
            var gerrierAccount = new BankAccount();
            gerrierAccount.AccountName = "Ms. Gerrier";
            gerrierAccount.Balance = 98;
            WriteLine(format: "{0}'s Balanace is {1:N} earned {2:C} interest.",
                arg0: gerrierAccount.AccountName,
                arg1: gerrierAccount.Balance,
                arg2: gerrierAccount.Balance * BankAccount.InterestRate);

            // Try Property
            var sam = new Person(initialName:"Sam", homePlanet:"Mars", initBirth: new DateTime(1972, 1, 27));

            WriteLine(sam.Origin);
            WriteLine(sam.Greeting);
            WriteLine(sam.Age);
            sam.FavoriteIceCream = "Stars";
            WriteLine($"{sam.Name}'s favorite icecream is {sam.FavoriteIceCream}");
            sam.FavoritePrimaryColor="red";
            WriteLine($"{sam.Name}'s favorite Color is {sam.FavoritePrimaryColor}");
            try{
                sam.FavoritePrimaryColor="yellow";
            }
            catch (ArgumentException argEx){
                WriteLine($"{argEx.GetType()} says {argEx.Message}");
            }
            // --------------------------------------
            // Flight Patterns(object pattern matching)
            // --------------------------------------
            WriteLine("// -------------------------------");
            WriteLine("//Flight Patterns(object pattern matching");
            WriteLine("// -------------------------------");
            var passengers = new object[5]{
                new FirstClassPassenger { AirMiles = 1_419 },
Esempio n. 4
0
        private static void Harry_Shout(object sender, EventArgs e)
        {
            Person p = (Person)sender;

            WriteLine($"{p.Name} is this angry: {p.AngerLevel}.");
        }