Optional argument in interface with no default value

I was surprised that C # uses the value for an optional method argument from an interface, and not from a class that implements this interface. For example:

using System;

public class Program
{
    private static IMyInterface instance;

    public static void Main()
    {
        instance = new MyClass();

        instance.PrintOpt();
        ((MyClass)instance).PrintOpt();
    }
}

public interface IMyInterface
{
    void PrintOpt(bool opt = false);
}

public class MyClass : IMyInterface
{
    public void PrintOpt(bool opt = true) 
    {
        Console.WriteLine($"Value of optional argument is {opt}");
    }
}

outputs the result:

The value of the optional argument is False

The value of the optional argument is True

My question is: is it possible to define an optional parameter in an interface without a default value or "overridable", so calling a method on an instance stored in an interface type variable uses an optional value defined in the class entering this interface?

+4
source share
1 answer

, , : .

, , , - , , . , :

IMyInterface interface = new MyClass();
MyClass theClass = (MyClass)interface;

interface.PrintOpt(); // false
theClass.PrintOpt(); // true

( #):

interface.PrintOpt(false);
theClass.PrintOpt(true);

" " " " IL - .

, , . , , , (, null default(int?)), . #, - COM VB , . , , -

comInterface.MyMethod(TheActualArgumentICareAbout, Type.Missing, Type.Missing, 
                      Type.Missing, Type.Missing, ...);

comInterface.MyMethod(argument, anotherSuperUseful: true);

- - , . , , - . , const. null , , "" , ( public static readonly of const, , enum).

+9

Source: https://habr.com/ru/post/1621488/


All Articles