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

Default Interface Methods क्या हैं

एक default interface method किसी promise को एक तैयार जवाब देता है, जैसे किसी job listing में एक standard training शामिल हो। Classes इसे वैसे ही उपयोग कर सकती हैं या अपने खुद के से replace कर सकती हैं।
Syntax
csharp
interface IInterfaceName
{
    void MethodName();

    void DefaultMethod()   // C# 8+ default implementation
    {
        MethodName();
    }
}

Default Interface Methods

C# 8 से, कोई interface किसी method के लिए एक default body प्रदान कर सकता है, जिसे implementing classes अपने आप inherit करती हैं जब तक वे इसे override न करना चुनें। यह आपको किसी मौजूदा interface में नए members जोड़ने देता है बिना उसे पहले से implement करने वाली हर class को तोड़े।

Default methods कुछ scenarios में अब भी सिर्फ interface type के ज़रिए call होने योग्य हैं, सीधे concrete class के ज़रिए नहीं, यह इस पर निर्भर करता है कि वे कैसे invoke होते हैं।

Note: Default interface methods हर implementer को इसे लिखने के लिए मजबूर किए बिना optional convenience behavior जोड़ने के लिए बढ़िया हैं।

उदाहरण: Default Interface Methods

markup
using System;

interface ILogger
{
    void Log(string message);

    void LogError(string message)
    {
        Log("ERROR: " + message);
    }
}

class ConsoleLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

class Program
{
    static void Main(string[] args)
    {
        ILogger logger = new ConsoleLogger();
        logger.Log("starting up");
        logger.LogError("something failed");
    }
}
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. यह भूल जाना कि default method सिर्फ interface type के ज़रिए उपलब्ध है, class type के ज़रिए नहीं।
  2. किसी ऐसे target framework पर default interface methods उपयोग करना जो उन्हें support नहीं करता।
  3. default implementations का ज़्यादा उपयोग करना, जो interfaces को abstract classes में बदल देता है।
🔒

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.