Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constant defined in an interface cannot be accessed without Interface name in the implemented class?

We have the interface and the implementing class:

pubic interface IStackContainer {
    const string DefaultStack = "default";
}

public class StackContainer<T> : MyBaseStackContainer<T>, IStackContainer{
    protected  internal string Stack {
        get { return Get(nameof(Stack), IInterface.DefaultStack); } //works fine
        set { Set(nameof(Stack), DefaultStack, value); }   //doesn't exist in the current context, why?
    }
}

Why can't I access the constant in the StackContainer without "IInterface."?

PS: my purpose here is to place the const somewhere instead of StackContainer in order to have easy access to it. If it was defined in the StackContainer I could use it like this: StackContainer.DefaultStack, but it isn't a good decision, I think.

like image 504
Eugene Maksimov Avatar asked Nov 04 '25 16:11

Eugene Maksimov


1 Answers

Trivially, because that's what the spec says.

I suspect this is to avoid the problems which come with multiple inheritance. Consider:

interface IA
{
    public const string DefaultStack = "default";
}

interface IB
{
}

class C : IA, IB
{
}

// Imagine this is allowed:
string stack = C.DefaultStack;

Imagine even that IA and IB are in different assemblies.

It's now a breaking change to add const string DefaultStack = "..." to IB, because that would make C.DefaultStack ambiguous. That effectively means that adding any const field to an interface is a breaking change, because that might conflict with a field of the same name in some other interface, and break some type which implements both of those interfaces somewhere.

like image 166
canton7 Avatar answered Nov 07 '25 10:11

canton7