(inspired by this comment)
Is there ever a situation in which you need to use the private
keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)
(inspired by this comment)
Is there ever a situation in which you need to use the private
keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)
Omitting the word 'private' would change the accessibility.
private
isn't about the runtime behaviour. It's to make your application maintainable. What's hidden byprivate
can only ever affect the code outside its class through thepublic
orprotected
members.So the answer is 'no' for runtime behaviour, 'yes' for developer behaviour!
In C# version 7.2 and later.
The
private protected
keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected
David Yaw's answer gave the most usual situation. Here is another one:
In
Account_generated.cs
:In
AccountHandCoded.cs
:The above code will not compile. The first "part" of
Account
requires the nested classHelper
to beprivate
. Therefore the attempt by the hand-coder to makeHelper
public must fail!However, had the first part of the class simply omitted the
private
keyword, all would compile.So for
partial
classes (and structs, interfaces), the access-level-free declarationmeans "the other 'parts' of this class are allowed to decide what the accessibility should be".
Whereas explicitly giving the default accessibility (which is
internal
for non-nested types andprivate
for nested ones) means "this class must have the most restricted access possible, and the other 'parts' cannot change that fact".