Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad programming practice to have "Public" members inside an "Internal" class?

Wouldn't it be more specific and appropriate if I only keep "protected", "internal" and "private" members (field, method, property, event) in a class which is declared as "internal"?

I have seen this practice (having "public" members in an "internal" class) in various code so just wanted to know is it a bad practice or does it has some benefit or advantage.

[Only concerned about C#] Thanks for your interest.

like image 821
Manish Basantani Avatar asked Jun 09 '10 14:06

Manish Basantani


People also ask

When should I make my class private?

You can only declare a class as private when it's nested within another class. Top-level classes can be made internal, however. You'd hide a class from the outside world when it's meant to be an implementation detail rather than providing an API everyone can use.

Should I use internal or public?

internal is useful when you want to declare a member or type inside a DLL, not outside that. Normally, when you declare a member as public , you can access that from other DLLs. But, if you need to declare something to be public just inside your class library, you can declare it as internal .

Can internal class have public members?

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.

What is the difference between internal and public class?

internal means that it's only accessible to other classes which are in the same assembly. Public means it's available to all other classes.


2 Answers

Not necessarily. If you want to implicitly implement an interface, then public members are more than acceptable.

Generally though, if the class is internal, public members don't make much sense. You won't get hurt, since you won't be able to expose the class in a strongly typed way outside of the module it is defined in, but if you aren't implicitly implementing an interface, there isn't much advantage.

like image 74
casperOne Avatar answered Nov 13 '22 03:11

casperOne


It's reasonable to assume that these public members are still part of the public interface of the class, even if the class itself has internal scope. When I see internal on a class member, this says to me 'somewhat dodgy backdoor access expressing tight coupling, whereas public still implies proper defensive programming responsibilities in my mind. It's purely a conceptual distinction.

like image 41
Dan Bryant Avatar answered Nov 13 '22 04:11

Dan Bryant