Aaron Anodide
Aaron Anodide

Reputation: 17196

What is the meaning of a public member of an internal class?

For example:

internal class C
{
    public void M()
    {
        Console.WriteLine("foo");
    }
}

To me, that reads "a method that can be accessed by anyone, regardless of assembly living inside a class that can only be accessed from code in the same assembly".

My experience with the compiler tells me that if I do something like that and do not get a warning, there is probably a valid reason to have it.

So, I suppose either

  1. Something is lacking in my understanding of protection levels.
  2. There could be a warning but there isn't one.

(if 2, this is not an attempt to complain about it - I just want to understand)

Upvotes: 7

Views: 804

Answers (4)

Eric Lippert
Eric Lippert

Reputation: 660533

To me, that reads "a method that can be accessed by anyone, regardless of assembly living inside a class that can only be accessed from code in the same assembly".

To me that means "the accessibility domain of C is restricted to this assembly; the accessibility domain of M is the unrestricted subset of the accessibility domain of its container, C".

"public" means that to me because that's what the specification says it means. I encourage you to read the portion of the specification which covers accessibility domains if you have questions or concerns about this.

Upvotes: 10

Steve Danner
Steve Danner

Reputation: 22198

See this SO Question for a detailed answer on how it functions.

In my experience, I like to mark internal members public in anticipation of a future time when I want to change the scope of the class to public. This way I can do that and all the previously marked internal methods are automatically public.

Upvotes: 5

Robert Harvey
Robert Harvey

Reputation: 180948

The internal keyword is going to limit access to M() to only calls made within the assembly in which C resides.

public just means anyone can access the member. public doesn't know or care anything about restrictions placed on it higher up in the class hierarchy, nor should it.

It's "by design," in other words. When you put public on a method, the compiler assumes you already know that, if you impose further restrictions on the class itself, then you must know what you are doing.

Upvotes: 5

Tony Hopkinson
Tony Hopkinson

Reputation: 20330

The scope of the class is internal, so while it doesn't seem to make sense to have public property, in that only those classes also in the name space will be able to see the class to see the property. If at some point you decided to make the class public it would be a massive PIA to go through every member and change it's scope.

Upvotes: 2

Related Questions