dotnet / dotnet/core

Calling Default Interface Methods needs casting - .NET Core 3.1

Open
#4,732 0 comments 2 reactions 0 assignees View on GitHub
Dominant language
PowerShell
Stars
22k
Forks
4.9k
Avg merge
5d 5h
Merged PRs (30d)
29

Description

Hello,

I'm not sure this is an issue or it's a known architectural limitation, but why can't I call an interface default method without casting it back to the original interface and why can't I call the method when I'm inheriting directly from the interface? Two scenarios below which look weird to me:

class Program
{
static void Main(string[] args)
{
IA classFromA = new MyClassFromA();
classFromA.DefaultFromA(); //Sounds good

MyClassFromA myClassFromA = new MyClassFromA();

//Why this doesn't work?
myClassFromA.DefaultFromA();

//Why do I need to cast back to class IA if MyClassFromA already inherits from IA?
((IA)myClassFromA).DefaultFromA();
}
}

public interface IA
{
public void DefaultFromA()
{
Console.WriteLine("Default method from A!");
}
}

class MyClassFromA : IA
{
public void SomeClassMethodFromA()
{
Console.WriteLine("Method from A!");

//If I inherit from A, why can't I call it from here?
DefaultFromA();
}
}

I think this gets worst in case someone has:
public interface IA { }
public interface IB : IA { }
public interface IC : IB { }
public interface ID : IC { }

Now the developer using ID has no clue on the available methods and must cast to each other interface to find the needed method... Couldn't it be available without casting, similar to an abstract class?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.