Exemplo n.º 1
0
        private static void ProblemWhenNotOverrideHashcode()
        {
            // Problem when not override GetHashcode
            var pe1 = new PersonE {
                FirstName = "Jeffrey", LastName = "Ye"
            };
            var pe2 = new PersonE {
                FirstName = "Jeffrey", LastName = "Ye"
            };
            Dictionary <PersonE, string> PersonPositionDic = new();

            PersonPositionDic.Add(pe1, "Software Engineer");
            PersonPositionDic.Add(pe2, "Mechanical Engineer");  // NOT report duplicate key error!

            string pos = PersonPositionDic[new PersonE {
                                               FirstName = "Jeffrey", LastName = "Ye"
                                           }];                                                       // Will throw KeyNotFoundException

            Console.WriteLine(pos);
            Console.WriteLine();
        }
Exemplo n.º 2
0
        private static void OverrideEqualOperator()
        {
            // How == will act when not override
            var pc1 = new PersonC {
                FirstName = "Jeffrey", LastName = "Ye"
            };
            var pc2 = new PersonC {
                FirstName = "Jeffrey", LastName = "Ye"
            };

            Console.WriteLine($"pc1.Equals(pc2): {pc1.Equals(pc2)}");
            Console.WriteLine($"pc1 == pc2: {pc1 == pc2}");
            Console.WriteLine();


            // Wrong implementation lead to infinite loop
            var pd1 = new PersonD {
                FirstName = "Jeffrey", LastName = "Ye"
            };
            var pd2 = new PersonD {
                FirstName = "Jeffrey", LastName = "Ye"
            };

            Console.WriteLine($"pc1 == pc2: {pd1 == pd2}");  // this will be a infinite loop
            Console.WriteLine();


            // Correct implementation
            var pe1 = new PersonE {
                FirstName = "Jeffrey", LastName = "Ye"
            };
            var pe2 = new PersonE {
                FirstName = "Jeffrey", LastName = "Ye"
            };

            Console.WriteLine($"pe1.Equals(pe2): {pe1.Equals(pe2)}");
            Console.WriteLine($"pc1 == pc2: {pe1 == pe2}");
            Console.WriteLine();
        }