3

the "override" of default interface impl of AcceptChanges does not call the default interface impl after casting this to interface type containing the default interface implementation. Why?

public interface IItemViewModel1
{
    void AcceptChanges() => Debug.Print("In interface");
}

public class ItemViewModelBase1<TModel> : IItemViewModel1
    where TModel : new()
{
    private TModel _data;

    public void AcceptChanges()
    {
        Debug.Print("In ViewModel");
        _data ??= new TModel();
        ((IItemViewModel1)this).AcceptChanges(); // calling itself rather than default interface implementation
    }
}

public static class TestClass
{
    public static void Test()
    {
        IItemViewModel1 x = new ItemViewModelBase1<int>();

        x.AcceptChanges();
    }
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
CleanCoder
  • 2,406
  • 1
  • 10
  • 35
  • According to the [meeting notes](https://github.com/dotnet/csharplang/blob/master/meetings/2017/LDM-2017-04-19.md#base-invocation), `base(IItemViewModel1).AcceptChanges()` should do it but it doesn't look like it was implemented. – Jeff Mercado Mar 06 '20 at 18:30
  • correct, this has been replaced by casting the object to interface type. I got this once working, but in this demo it does not work and I don't know why – CleanCoder Mar 06 '20 at 18:31
  • I'm not sure you can dot it. I checked this documentantion and doesn't mention nothing like it. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods – Claudio Torres Mar 06 '20 at 18:59
  • They tried as hard as they could to make this code not work. Not the intention of default interface implementation, it is a refactoring tool. Gets you out of trouble when you need to add a method to an interface but can't change the code of an assembly that implements the interface. – Hans Passant Mar 06 '20 at 18:59
  • More [design decisions](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#base-interface-invocations-round-2-closed), but they also don't seem to work – Pavel Anikhouski Mar 06 '20 at 19:11
  • The links are to meeting notes and proposals, not the final syntax. This was cut in April 2019 because there was no time to add the required runtime support – Panagiotis Kanavos Mar 09 '20 at 11:16
  • Runtime support and JIT optimizations allow DIMs to [work without boxing](https://stackoverflow.com/questions/57827493/calling-c-sharp-interface-default-method-from-implementing-struct-without-boxing/57852764#57852764) for example. 3.1 is an LTS version too, which means that any quirky behavior would have to be maintained for years. – Panagiotis Kanavos Mar 09 '20 at 11:20

0 Answers0