0

Let's say we have a situation like this:

    // Declare `Nested` struct inside class and interface

    class Base {
        public struct Nested {}
    }
    interface IBase {
        public struct Nested {}
    }

    // Inherit them

    class ThroughClass: Base {}
    class ThroughInterface: IBase {}

    // Try reaching `Nested` class through above types

    class Test {
        ThroughClass.Nested c;     // OK
        ThroughInterface.Nested i; // Error CS0426: The type name 'Nested' does not exist in the type 'ThroughInterface'
    }

Why it's not possible to reach Nested here using ThroughInterface? Is this a compiler bug, or design choice (I can't find any documentation related to that)?

Smilediver
  • 1,738
  • 23
  • 26
  • https://stackoverflow.com/questions/15009073/interfaces-cannot-declare-types – Garr Godfrey Dec 03 '20 at 13:23
  • `ThroughInterface` doesn't inherit `Base`, `ThroughClass` does. – ProgrammingLlama Dec 03 '20 at 13:24
  • 4
    @GarrGodfrey That question is from before C#8, when DIM was introduced. It is now legal to declare a type within an interface (although you'd access it using `IBase.Nested`: I'm trying and failing to find where that's specified) – canton7 Dec 03 '20 at 13:25
  • @John `ThroughInterface` implements `IBase`, which defines its own `Nested` type – canton7 Dec 03 '20 at 13:25
  • 1
    Implementing an interface isn't the same thing as inheriting a base class though. – ProgrammingLlama Dec 03 '20 at 13:27
  • does using IBase.Nested work? I think @John is right, that implementing the interface is different. `ThroughInterface` *could* have it's own `Nested` type that is distinct from the IBase.Nested type – Garr Godfrey Dec 03 '20 at 13:29
  • If you read the bottom of the question, OP is asking whether the fact that `ThroughInterface.Nested` doesn't work is a design decision or compiler bug. An answer would therefore include a link to the docs which say this is or isn't supposed to work – canton7 Dec 03 '20 at 13:44
  • @canton7 My point is that I don't really follow OP's logic that it should work, because OP is comparing apples to oranges. – ProgrammingLlama Dec 03 '20 at 13:48
  • 1
    Indeed, that distinction is made by the compiler. The best reference which actually states that which I can find is https://learn.microsoft.com/en-gb/dotnet/csharp/tutorials/default-interface-methods-versions, see the paragraph "That cast from SampleCustomer to ICustomer is necessary.". There's also https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods#concrete-methods-in-interfaces, which talks about methods in general but does say "members", which includes nested types – canton7 Dec 03 '20 at 13:54

0 Answers0