Warm tip: This article is reproduced from serverfault.com, please click

Access modifiers related to interface

发布于 2020-12-02 02:50:01

I am confused over the below paragraph found in https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

Normally, the accessibility of a member isn't greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.

Could anyone help to give an example of the last sentence? If the class is internal, then no instance of the class can be created outside the assembly. How is it possible that one can access a member of such class from outside the assembly, even if the member is declared public?

Thanks

Questioner
user_defined_function
Viewed
0
Llama 2020-12-02 10:54:19

Imagine you create the following service and interface:

public interface IFoo
{
    void Bar();
}

internal class ConcreteFoo : IFoo
{
    public void Bar()
    {
        Console.WriteLine("Hello from my concrete foo!");
    }
}

You then expose a factory:

public class Factory
{
    public IFoo CreateFoo()
    {
        return new ConcreteFoo();
    }
}

The Bar method is implementing the interface requirement of void Bar(); in IFoo. While consumers can't instantiate a ConcreteFoo, it's possible for other entities within your library to create and return a ConcreteFoo boxed as an IFoo (which is public), thereby allowing access to the member in the consuming code.