(연관된 글이 1개 있습니다.)
                    
                    
                    선생님 안녕하세요!!
namespace example
{
    public class Menu
    {
        private string Name;
        private int Price;
        public Menu(string Name, int Price)
        {
            this.Name = Name;
            this.Price = Price;
        }
        public override bool Equals(Object obj)
        {
            Menu other = obj as Menu;
            if (other == null)
                throw new ArgumentException();
            return this.Name == other.Name && this.Price == other.Price;
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode() + Price.GetHashCode();
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Menu order1 = new Menu("통새우와퍼세트", 8500);
            Menu order2 = new Menu("통새우와퍼세트", 8500);
            Console.WriteLine(order1.GetHashCode());
            Console.WriteLine(order2.GetHashCode());
        }
    }
}
위의 코드는 제가 다른 코드를 수정한 코드입니다.
① GetHashCode()를 재정의 하지 않으면 order1.GetHashCode() ≠ order2.GetHashCode()이지만
재정의 하는 순간 단지 Name과 Price의 해시값을 더했을 뿐인데 어떻게 order1.GetHashCode() = order2.GetHashCode()가 되는 이유가 궁금합니다.
② return Name.GetHashCode() + Price.GetHashCode(); 가 아닌 return Name.GetHashCode(); 만 입력해도 해시값은 동일하게 나옵니다.. 
그렇다면 GetHashCode()의 본문은 다양한 형태로 작성될 수 있는데 혹시 GetHashCode() 메서드를 오버라이드 할 때 따로 기준이 따로 있나요?
③ 보통 책이나 다른 예제를 참고하면 
return Name.GetHashCode() * 31 + Price.GetHashCode(); 와 같이 소수 31을 곱하던데 따로 이유가 있나요?
검색해보니까 관행적으로 소수 31를 곱한다고 되어 있지만 
어떤 숫자를 곱하더라도 두 개의 값은 동일하게 나오지만 물론 곱하지 않더라도 해시값이 동일하게 출력되는데 말이죠...
        
        [연관 글]
                    
                    
                    
                    
                    
    
                    
                    
                    
                    
                    
                
                    [최초 등록일: ]
                    [최종 수정일: 4/5/2021]