Generic Constraints का उपयोग
Generic constraints यह नियम हैं कि किसी generic में कौन सी types की अनुमति है, जैसे एक club जो सिर्फ swim करने वालों को accept करता है। वे code को type की कुछ features सुरक्षित रूप से उपयोग करने देते हैं।
In this page:
Syntax
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
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"));
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
where T : new()भूल जाना और फिरnew T()call करना, जो एक compile error है।- constraints को गलत order में रखना, जैसे
new()को किसी class constraint से पहले। - ऐसी type पास करना जो constraint को satisfy नहीं करती, जो एक compile error है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: