← Back to C# Course | Chapter 11: Generics | Lesson 3 of 6

Generic Constraints का उपयोग

Generic constraints यह नियम हैं कि किसी generic में कौन सी types की अनुमति है, जैसे एक club जो सिर्फ swim करने वालों को accept करता है। वे code को type की कुछ features सुरक्षित रूप से उपयोग करने देते हैं।

In this page:

  1. Generic Constraints
Syntax
csharp
static T MethodName<T>(T a, T b) where T : IComparable<T>
{
    // body
}

class ClassName<T> where T : class, new() { }

Generic Constraints

Constraints सीमित करते हैं कि किसी generic के type argument के रूप में कौन सी types उपयोग की जा सकती हैं, where T : ... उपयोग करते हुए।

आम constraints के लिए एक class, एक struct, एक parameterless constructor (new()), या किसी specific interface का implementation चाहिए होता है। Constraints generic code को सुरक्षित रूप से ऐसे members call करने देते हैं जो हर संभव type पर उपलब्ध नहीं होते।

Note: जब आपके generic method को T type की दो values compare करनी हों तब where T : IComparable<T> उपयोग करें।

उदाहरण: Generic Constraints

markup
using System;

class Program
{
    static T Max<T>(T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Max(3, 7));
        Console.WriteLine(Max("apple", "banana"));
    }
}
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. where T : new() भूल जाना और फिर new T() call करना, जो एक compile error है।
  2. constraints को गलत order में रखना, जैसे new() को किसी class constraint से पहले।
  3. ऐसी type पास करना जो constraint को satisfy नहीं करती, जो एक compile error है।
🔒

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.