2

Since class members are private by default in C# and the best code is no code at all, does idiomatic C# omit declaring private members as private to avoid clutter? Or is it more common to be explicit?

To be clear, I'm not asking what everyone's opinion on the matter is, but which is more common in well-established code bases (I'm fairly new to C#).

Matt Kline
  • 10,149
  • 7
  • 50
  • 87
  • Follow your preference. If anyone cares that you explicityly declared something `private`, they're being picky and wasting your and their time. IMHO – Khan Jul 30 '13 at 13:41
  • Microsoft seems to do it in the .NET Framework Libraries. – Magnus Jul 30 '13 at 13:45

3 Answers3

4

Possible duplicate of Why explicitly write "private"?. I think it's best practice to explicit declare them as private. Your code becomes more readable, especially for others... Main reason is that private is not the default access level in every language, as the accepted answer in the above question says.

Community
  • 1
  • 1
Jeroen1984
  • 1,616
  • 1
  • 19
  • 32
4

Personally, I declare them as private, in case someone else picks up the code and makes an assumption which may be incorrect, or decide to change the scope level (thinking that you had forgotten to place score against the member).

Also, some other languages, may have different default implementations, so if a new member of your team is picking up C# for the first time, explicit deceleration will help them.

Found this on C# best practices on Safari Books:

Always explicitly use a scope keyword for all types and members.

Why: The default scope for Visual Basic type members is Public, whereas the default scope for C# is private. Omitting the scope keyword might disorient developers who are more familiar with other languages.

Christian Phillips
  • 18,399
  • 8
  • 53
  • 82
  • Don't forget the default for Java is most similar to `internal` (no direct equivalent). But `private` is always `private`. – Sam Harwell Jul 30 '13 at 14:03
1

Most C# style guides seem to favor explicit over implicit. For example, StyleCop will pretty much always complain if an object of any type (class, interface, field, property, method, etc.) is declared without an access modifier.

My personal preference would also be to always include the private keyword, because it makes it easier to see at a glance that the member is private. If there's no access modifier my brain sort of has to go through a two-step process where it first needs to identify that there's no access modifier, and then remember that no modifier = private.

What makes it more complicated is the fact that for instance on classes, no access modifier = internal. I understand why fields/properties/methods and classes/interfaces need to differ in this regard, but I dislike the fact that the lack of an access modifier changes its meaning depending on the object type.

But all of this is of course highly debatable.

Magnus Grindal Bakken
  • 2,083
  • 1
  • 16
  • 22