Skip to content

Calling Default Interface Methods needs casting - .NET Core 3.1 #4732

@ccarlo88

Description

@ccarlo88

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions