Skip to content

Understanding how static abstract/virtual interface methods interact with inheritance #7922

Answered by 333fred
alexthornton1 asked this question in Q&A
Discussion options

You must be logged in to vote

Shouldn't it have inherited it from BaseThing?

Yes, but not in the way that you're thinking. Let's translate this to an instance-based version of the code:

DoAndPrint<DerivedThing>();

static void DoAndPrint<T>() where T : ICanDo<T>, new()
{
    Console.WriteLine(new T().Do());
}

public interface ICanDo<T> where T : ICanDo<T>
{
    virtual string Do() => throw new NotImplementedException();
}

public abstract class BaseThing<T> : ICanDo<T> where T : ICanDo<T> { }

public class DerivedThing : BaseThing<DerivedThing>
{
    public string Do() => "DerivedThing";
}

Note here that we see the same behavior: a not-implemented exception is thrown. We can also see this if we move from a static v…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@alexthornton1
Comment options

Answer selected by alexthornton1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants