As far as I know, private
is the default everywhere in C# (meaning that if I don't write public
, protected
, internal
, etc. it will be private
by default). (Please correct me if I am wrong.)
So, what's the reason to write that keyword, or why does it even exist for members?
For example, when an event handler is auto-generated it looks like this:
private void RatTrap_MouseEnter(object sender, CheeseEventArgs e)
{
}
But why does it even write private if that's implied and default? Just so that novice developers (who don't know it's the C# default) know that it's private? Or is there a difference for the compiler?
Moreover, is there a case where writing "private" (alone) will change the accessibility of the member?
One good reason for explicitly specifying the visibility is so that you don't have to think about what is the default for the context you are in.
Another good reason is because FxCop tells you to do it.
I'd say for consistency with the readability of the scope of the rest of the class.
Readability, demonstration of intent are two great reasons I can think of.
A lot of people (people like me!) regularly program in a handful of different languages. Being explicit with things like these prevents me from needing to remember all the arcane details of all the languages I program in.
Not quite - the default is "the most restricted access available for this declaration". So for example, with a top-level type the default is
internal
; for a nested type the default isprivate
.It makes it explicit, which is good for two reasons:
As for your last part:
Yes, for making half of a property more restrictive than the other:
I used to go with defaults everywhere I could, but I've been convinced (partly by Eric Lippert) that making it clear that you've thought about it and decided to make something private is a good idea.
Personally I wish there were a way of doing that for sealed / unsealed, too, for type declarations - possibly not even have a default. I suspect that many developers (myself included if I'm not careful) leave classes unsealed just because it's less effort than making them sealed.
Readability - Not everyone may know that private is the default behaviour.
Intent - Gives a clear indication that you have specifically declared the property private (for whatever reason).