Considering "private" is the default access modifier for class Members, why is the keyword even needed?
While the public access modifier allows a code from outside or inside the class to access the class's methods and properties, the private modifier prevents access to a class's methods or properties from any code that is outside the class.
Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of the same package will not be able to access these members.
private Access ModifierThe private keyword is used to create private members (data and functions). The private members can only be accessed from within the class. However, friend classes and friend functions can access private members.
The private keyword is an access modifier used for attributes, methods and constructors, making them only accessible within the declared class.
It's for you (and future maintainers), not the compiler.
There's a certain amount of misinformation here:
"The default access modifier is not private but internal"
Well, that depends on what you're talking about. For members of a type, it's private. For top-level types themselves, it's internal.
"Private is only the default for methods on a type"
No, it's the default for all members of a type - properties, events, fields, operators, constructors, methods, nested types and anything else I've forgotten.
"Actually, if the class or struct is not declared with an access modifier it defaults to internal"
Only for top-level types. For nested types, it's private.
Other than for restricting property access for one part but not the other, the default is basically always "as restrictive as can be."
Personally, I dither on the issue of whether to be explicit. The "pro" for using the default is that it highlights anywhere that you're making something more visible than the most restrictive level. The "pro" for explicitly specifying it is that it's more obvious to those who don't know the above rule, and it shows that you've thought about it a bit.
Eric Lippert goes with the explicit form, and I'm starting to lean that way too.
See http://csharpindepth.com/viewnote.aspx?noteid=54 for a little bit more on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With