A class which implements comparison and equality interfaces : IEquatable « Class « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Class » IEquatable 
7.55.1.A class which implements comparison and equality interfaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

class Person : IComparable<Person>, IEquatable<Person>, IComparable
{
    public string Name;
    public int Age;
    public string Company;

    // Implements IComparable<Person>.CompareTo:
    public int CompareTo(Person other)
    {
        if (other == null)
            return -1;
        return this.Name.CompareTo(other.Name);
    }

    // Implements IComparable.CompareTo:
    public int CompareTo(object obj)
    {
        Person p = obj as Person;
        return CompareTo(p);
    }

    // Implements IEquatable<Person>.Equals:
    public bool Equals(Person other)
    {
        return ((IComparable<Person>)this).CompareTo(other== 0;
    }

    // Overrides Object.Equals:
    public override bool Equals(object obj)
    {
        Person p = obj as Person;
        return Equals(p);
    }
}

public class MainClass
{
    public static void Main()
    {
        Person[] people = new Person[3];
        people[0new Person();
        people[0].Name = "S D"; people[0].Age = 20; people[0].Company = "E";
        people[1new Person();
        people[1].Name = "M M"; people[1].Age = 40; people[1].Company = "C";
        people[2new Person();
        people[2].Name = "J D"; people[2].Age = 30; people[2].Company = "T";

        foreach (Person p in people)
            Console.Write("'{0},{1},{2}'\t", p.Name, p.Age, p.Company);
        Console.WriteLine();

        Array.Sort(people);

        foreach (Person p in people)
            Console.Write("'{0},{1},{2}'\t", p.Name, p.Age, p.Company);
    }
}
'S D,20,E'      'M M,40,C'      'J D,30,T'
'J D,30,T'      'M M,40,C'      'S D,20,E'
7.55.IEquatable
7.55.1.A class which implements comparison and equality interfaces
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.