← Back to C# Course | Chapter 8: Interfaces | Lesson 5 of 6

IComparable क्या है

IComparable objects को compare होने देता है ताकि उन्हें sort किया जा सके, जैसे बच्चों को height के अनुसार लाइन में खड़े होना सिखाना। कोई object यह बताना सीखता है कि वह किसी दूसरे से पहले आता है या बाद में।

In this page:

  1. IComparable
Syntax
csharp
class ClassName : IComparable<ClassName>
{
    public int CompareTo(ClassName other)
    {
        return this.Value.CompareTo(other.Value);   // <0, 0, >0
    }
}

IComparable

IComparable<T> एक single method, CompareTo, define करता है, जो objects को अपना natural ordering define करने देता है।

इसे implement करना किसी type को बिना किसी अतिरिक्त comparer के Array.Sort या List<T>.Sort से sort होने देता है। CompareTo less-than, equal, या greater-than बताने के लिए negative, zero, या positive return करता है।

Note: IComparable<T> implement करें जब भी किसी type का एक स्पष्ट natural sort order हो, जैसे कोई numeric score।

उदाहरण: IComparable

markup
using System;
using System.Collections.Generic;

class Player : IComparable<Player>
{
    public string Name;
    public int Score;

    public Player(string name, int score)
    {
        Name = name;
        Score = score;
    }

    public int CompareTo(Player other)
    {
        return Score.CompareTo(other.Score);
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Player> players = new List<Player>
        {
            new Player("Ana", 50),
            new Player("Ben", 90),
            new Player("Cid", 20),
        };

        players.Sort();

        foreach (Player p in players)
        {
            Console.WriteLine($"{p.Name}: {p.Score}");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. class पर : IComparable<Player> declare करना भूल जाना, जिससे list.Sort() एक InvalidOperationException फेंकता है क्योंकि items compare नहीं हो सकते।
  2. CompareTo से गलत sign return करना, जिससे list विपरीत order में sort होती है; इसे negative number देना चाहिए अगर यह object पहले आता है, equal होने पर zero, और अन्यथा एक positive number।
  3. CompareTo को Score - other.Score के रूप में implement करना, जो बड़ी values के लिए overflow हो सकता है और गलत result दे सकता है; इसके बजाय Score.CompareTo(other.Score) का उपयोग करें।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.