Class behaves properly using overridden Equals and GetHashCode methods : Hash Code « Development Class « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Development Class » Hash CodeScreenshots 
Class behaves properly using overridden Equals and GetHashCode methods
Class behaves properly using overridden Equals and GetHashCode methods


using System;
using System.Collections;

public class GoodCompare {
  public static void Main() {
    Name president = new Name ("A""B");
    Name first = new Name ("C""D");
    Console.WriteLine("The hash codes for first and president are: ");
    
    if (president.GetHashCode() == first.GetHashCode())
       Console.WriteLine("equal");
    else
       Console.WriteLine("not equal");
    
  }
}



public class Name {
  protected String first;
  protected char initial;
  protected String last;
          
  public Name(String f, String l) {
    first = f; 
    last = l; 
  }
  public Name(String f, char i, String lthis(f,l) {
    initial = i;  
  
  public override String ToString() {
    if (initial == '\u0000')
       return first + " " + last;
    else  
       return first + " " + initial + " " + last;
  }
  public override bool Equals(Object o) {
    if (!(o is Name))
       return false;
    Name name = (Name)o;
    return first == name.first && initial == name.initial
             && last == name.last;
  }
  public override int GetHashCode() {
    return first.GetHashCode() (int)initial 
                             + last.GetHashCode();
  }

}


           
       
Related examples in the same category
1.Get the Hash code for string valueGet the Hash code for string value
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.