9

What is the use of the private keyword if everything, by default, is private?

public class A {
    object someObject;
    private object someOtherObject;
}

Wouldn't both of the above be private? If they're both private then why the need for the keyword itself?

MyNameIsJob
  • 2,508
  • 2
  • 17
  • 17
  • 5
    The default isn't private for *everything*: The default for class/struct members is private; the default for top-level types is internal. http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx – LukeH Dec 13 '10 at 16:04
  • Duplicate (even though this question was first): http://stackoverflow.com/questions/8479214/any-reason-to-write-the-private-keyword-in-c – Jon May 17 '12 at 01:33
  • Duplicates older than this thread: [Should you use the private access modifier if it's redundant?](http://stackoverflow.com/questions/254912/) and [What for should I mark private variables as private if they already are?](http://stackoverflow.com/questions/552857/). – Jeppe Stig Nielsen Sep 12 '13 at 15:02

4 Answers4

21

Explicit use of the keyword clarifies the code, whatever the default is.

Avoid guesswork or the need for fact-checking on the part of code reader/maintainer, where possible.

There is a reference for the visibility information via this prior question.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
9

As Steve Townsend said, it clarifies code, but it's also useful in properties with mixed access, e.g.:

public int SomeProperty { get; private set; } 
Community
  • 1
  • 1
jball
  • 24,791
  • 9
  • 70
  • 92
3

The default has changed from time to time. It used to be in VB that everything was public by default. Now it's private.

In other programming languages, the default is different.

So, writing it out helps the reader of the code.

DOK
  • 32,337
  • 7
  • 60
  • 92
  • 2
    Changing the default in an established language like C# would be a massive breaking change. The likelihood of this happening is very small, I would imagine. – LukeH Dec 13 '10 at 16:06
  • 3
    @fingerprint211b: That's true, but many would consider VB6 and VB.NET to be separate dialects rather than just an increment of the version-number. – LukeH Dec 13 '10 at 16:20
1

Code cleanliness is next to Godly-ness. Makes it easy to read.

Ryan Bennett
  • 3,404
  • 19
  • 32