128

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
  • 18
    IIRC, a "top-level" type will be `internal` by default however. – Jeff Mercado Dec 12 '11 at 18:43
  • 5
    The default for everything is not private, as indicated, and as a general rule of thumb it's better to be explicit. – James Michael Hare Dec 12 '11 at 18:45
  • 1
    Related: [Does C# need the private keyword?](http://stackoverflow.com/questions/6349269/does-c-sharp-need-the-private-keyword) – BoltClock Jan 09 '12 at 13:30
  • 2
    The default for everything is "as private as possible." Obviously a non-nested class can't be private, or nothing could instantiate or use it. But members are private by default, and nested classes are private by default. Everything in C# has, by default, the most restricted level of visibility it can have. – Ryan Lundy Jan 10 '12 at 21:24
  • Other threads: [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:01
  • You asked a good question the wrong way. You shouldn't have said "AFAIK private is the default", which is not a true statement. That being said, I agree `private` is a pretty much redundant keyword. – Shimmy Weitzhandler May 26 '17 at 11:16
  • Possible duplicate of [Why explicitly write "private"?](https://stackoverflow.com/questions/4113651/why-explicitly-write-private) – vinibrsl Sep 13 '17 at 18:46

10 Answers10

182

AFAIK, 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 wrong).

This is not true. Types defined within a namespace (classes, structs, interfaces, etc) will be internal by default. Also, members within different types have different default accessibilities (such as public for interface members). For details, see Accessibility Levels on MSDN.

Also,

So, what's the reason to write that keyword, or why does it even exist?

Specifying this explicitly helps denote your intention to make the type private, very explicitly. This helps with maintainability of your code over time. This can help with other developers (or yourself) knowing whether a member is private by default or on purpose, etc.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    @Wayne : he have an answer with higher score than Jon Skeet but he doesn't deserve it... The Jon answer is a lot more accurate . – aleroot May 02 '12 at 05:39
  • 4
    This is a pointless distinction. Types within a namespace are internal by default because they *can't* be private by default; otherwise nothing could use them. They're still as restricted as they can possibly be, by default. – Ryan Lundy May 17 '12 at 03:52
  • 1
    Default members accessibility for inisde classes and struct is private. Check here: http://msdn.microsoft.com/en-us/library/ba0a1yw2(v=vs.90).aspx – Mitja Bonca Jul 21 '12 at 10:09
  • But elements inside a namespace cannot be `private`. – Shimmy Weitzhandler May 26 '17 at 11:14
  • Also, `get` and `set` default to the accessibility of the property itself – AustinWBryan Sep 04 '18 at 00:52
131

AFAIK, private is the default everywhere in C#

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 is private.

So, what's the reason to write that keyword, or why does it even exist?

It makes it explicit, which is good for two reasons:

  • It makes it clearer for those who don't know the defaults, as per your question (I've never liked this argument, personally, but I figured it's worth mentioning)
  • It gives an impression that you've deliberately decided to make it private, rather than just gone with the defaults.

As for your last part:

Moreover is there a case where writing "private" (alone) will change the accessibility of the member?

Yes, for making half of a property more restrictive than the other:

// Public getter, public setter
public int Foo { get; set; }

// Public getter, private setter
public int Bar { get; private set; }

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.

Tesserex
  • 17,166
  • 5
  • 66
  • 106
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1. Using otherwise-irrelevant keywords to signal semantic intent is useful, although my Java background makes the use of `final` a more typical example. – jprete Dec 12 '11 at 21:05
  • 1
    @minitech: The other way round works too, but is less useful. This was all introduced in C# 2. – Jon Skeet Dec 13 '11 at 05:19
  • 24
    I certainly wish there were no defaults at all and the compiler just threw an error if the access modifier was missing. I don't think most people know what the defaults are for every situation, which then leads to unintended errors. –  Dec 13 '11 at 19:44
  • +1 "for a nested type the default is private" - I just know about this when I read your answer. Thanks! – Nordin Dec 15 '11 at 02:47
  • 6
    @Phong, for C# there's one easy rule: *By default, everything is as private as it can be.* Items in a namespace such as non-nested classes can't be private, because nothing could use them. They can only be internal or public; so by default, they're internal. Things inside of other things (enums within a class; nested classes; properties; fields; methods...) are private by default. – Ryan Lundy May 21 '12 at 17:26
  • @JonSkeet Given Roslyn now prompts you to remove "redundant" modifiers, has your opinion on this changed at all? – Obsidian Phoenix Jul 21 '15 at 08:21
  • @ObsidianPhoenix: I don't see any such prompts. Perhaps you've specified an option somewhere? – Jon Skeet Jul 21 '15 at 08:42
  • @JonSkeet I'm getting it in a new VS2015 console app. Getting lightbulbs on `internal class` and `private void DoWork()`, etc. – Obsidian Phoenix Jul 21 '15 at 08:44
  • @ObsidianPhoenix: Possibly a plugin? I'm not seeing it in my VS2015 installation. Either way, it wouldn't change my opinion :) – Jon Skeet Jul 21 '15 at 08:45
  • @JonSkeet aha. Refactoring Essentials for 2015 (recommended by [Hanselmann](http://www.hanselman.com/blog/VSRefactoringEssentialsFormerlyNR6PackFreeAnalyzersAndRefactoringForVisualStudio2015.aspx)). I'm of the same opinion myself - I prefer explicitness. – Obsidian Phoenix Jul 21 '15 at 08:53
  • @ObsidianPhoenix: I'd hunt for an option then, and make a feature request if you can't find one :) – Jon Skeet Jul 21 '15 at 09:01
  • That's a good point with `sealed`/`unsealed`. I always use `private` so I am always forced think about whether or not it's the right choice, however, I never make classes sealed for probably the same reason you mentioned. I never have to write `unsealed` so I never have to think about it. – AustinWBryan Sep 04 '18 at 00:56
  • The idea that one should make things `private` so as to communicate that one has *deliberately* decided to make them private is an odd notion to me. *Everything* should have a scope as restricted as possible. You should only have to be deliberate about making things *not* private. That's why the defaults in C# are so well-thought-out; if you leave off the visibility modifiers, C# does the right thing. You *add* the modifier in order to show deviations from the ideal. – Ryan Lundy Mar 12 '19 at 13:59
  • @RyanLundy: Yes, they're well thought-out, but I still think it's good to communicate that it was a deliberate decision. IMO it reduces the risk that someone will make it public thinking it was just *accidentally* private. – Jon Skeet Mar 12 '19 at 14:07
  • @JonSkeet People who don't believe in the principle of Chesterton's fence won't be stopped by the presence of `private`. ;) – Ryan Lundy Mar 12 '19 at 15:43
17

private adds visual clutter. To those who insist that it makes things explicit, I would ask: Do you do this with mathematics, too? For instance:

var answer = a + b / c;

Do you find that unclear without redundant parentheses around b / c?

The rule in C# is very simple: By default, everything is as close to private as it can be. So if you need something to be more visible than the default, add a modifier. Otherwise, don't add needless keywords to your code.

Ryan Lundy
  • 204,559
  • 37
  • 180
  • 211
  • 3
    I used to agree with this right before asking the question. But, some people write VB, some C++, some even F# (coming from other functional languages such as Haskell perhaps?), better than they do on C#. So, for them (and for us if we forget about it after 2 years of no c#ing) it's better if accessors are explicit. Don't undervalue the impact easy learning has on a project, many developers come from backgrounds which may not reflect the tool of choice, and they do need learning aids, even in production code, this is not bad at all (and we know many code very bad C#, so a few aids help us too). – Camilo Martin Jan 11 '12 at 02:20
  • In addition, math is something we learn for more than a decade on schools. C# can't be compared to that (I'd agree if we were talking about removing meaningless parentheses in mathematical expressions). – Camilo Martin Jan 11 '12 at 02:20
  • 4
    Well, sure, in VB the defaults are atrocious. I think the default visibility is `Friend` for members, for instance. C# does its visibility defaults the right way: Things are set to least visibility possible unless they're changed. From what I'm able to find, it appears the same is true for C++ (except structs). (It doesn't appear to be true for F#.) – Ryan Lundy Jan 11 '12 at 04:22
  • In any case, a C# programmer writing VB could think "the .NET defaults seem to be alright!" and forget about the... uhm, differences the two languages have. And if you think the VB defaults are bad, look at javascript... closures being the only way out of the global scope. So being able to be clear about intentions is better in a world so full of differences. – Camilo Martin Jan 11 '12 at 06:23
  • 12
    It's strange to me that so many people are in favor of `var`, because it cuts down on visual clutter, and yet so many people are in favor of pointlessly typing `private`. – Ryan Lundy Jan 11 '12 at 16:36
  • 4
    I would even go so far as to argue that visual clutter *inhibits* readability! – binki Feb 15 '15 at 01:37
  • 2
    upvoted even though I *do* prefer to use parentheses in the case of your math example. – Marc.2377 Dec 19 '18 at 21:00
  • Agree var is horribly overused in c# world. Usually I use it when developing a WIP then let VS replace with explicit type. Makes reading harder, and should appear fairly rarely in production code in my view. However, do agree with @Marc.2377 that I would want parentheses for the example. – MemeDeveloper Jun 26 '22 at 16:07
  • @MemeDeveloper That's not the point I was making; in fact I think `var` should be used as often as possible. A lot of developers use the type as a crutch instead of creating good variable names. Furthermore, the leading type is usually redundant, and leaves more to refactor when a type changes. – Ryan Lundy Jun 26 '22 at 16:43
  • Agree that good naming in general is usually essential for quality, readable code (certainly in C#). Agree that dev crutches should be avoided, but I don't think that var is generally a good thing. If you are declaring and assigning by newing up on same line then yes it can be useful. I aim to make reading code easier, and often see e.g. var myUselessName = SomeOtherBadlyNamedThing.SomeObscureMethod(); which means readers need VS (or similar) to hover for intellisense just to find out what they are dealing with. All to avoid typing a few chars for a Type. – MemeDeveloper Jun 26 '22 at 21:58
  • I believe one of the best things about C# is the strong typing so why hide it. var to me is (generally) lazy / a bad fad. I use it while rapidly developing then use VS to refactor to explicit types. So yes I get the refactoring tooling point, but I would not often be changing types once past that rapid dev stage. Usually things have solidified by the time I refactor to explicit types and not often needing var. End of the day if the compiler knows why not let the reader know. – MemeDeveloper Jun 26 '22 at 22:00
  • I want to know the types I am dealing with (at a glance) in my book the types of instances are very far from redundant. – MemeDeveloper Jun 26 '22 at 22:03
  • But we all have diff personal preferences / conventions. Whatever works for you really ! Certainyl we agree on this "private adds visual clutter." – MemeDeveloper Jun 26 '22 at 22:04
7

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James
  • 80,725
  • 18
  • 167
  • 237
6

Readability, demonstration of intent are two great reasons I can think of.

Maess
  • 4,118
  • 20
  • 29
  • Agreed. E.g. if you're working with other developers on a bit of code, setting something to private helps to indicate your intent. It's also helpful when you jump back into your code after a number of years and your IDE can tell you what methods should be publicly accessible for that class. – Aaron Newton Dec 13 '11 at 22:53
6

As far as I know, private is the default everywhere in C#

Explicitly declaring private, means you know it is private. Not just think it is, because as far as you know, it is the default. It also means that someone else who looks at the code knows what it is.

There is no "I think it is", "I'm pretty sure it is", etc. It just is. And everyone is on the same page.

I am not a C# developer. If I had to work with some code that wasn't explicitly declared private, I would probably assume it was internal.

I dislike when things are implicitly set. It's never as clear as when they are explicitly set.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JD Isaacks
  • 56,088
  • 93
  • 276
  • 422
  • Sounds reasonable, I even forget basics of languages I once knew better. – Camilo Martin Dec 12 '11 at 21:47
  • "I dislike when things are implicitly set. It's never as clear as when they are explicitly set." but aren't there like a bazillion things implicit in program code? Don't we use high-level languages, libraries, syntactic sugar and sane defaults so we don't have to think about and state all the details? In my book less details and code is gooder and trumps being explicit for the sake of being explicit. Not writing private is like var. – One Man Monkey Squad Nov 03 '22 at 10:38
5

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.

davidtbernal
  • 13,434
  • 9
  • 44
  • 60
  • 2
    Well I wouldn't say "default access modifier is `private`" is an *arcane detail*... But I understand the point. The other day I had trouble remembering how the framework I used last week ([MEF](http://en.wikipedia.org/wiki/Managed_Extensibility_Framework)) worked. – Camilo Martin Dec 31 '11 at 02:28
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
  • +1, I just noticed about FxCop complaining about me removing the private modifier now when I built with the change. – Camilo Martin Dec 12 '11 at 18:58
  • 1
    Don't agree that doing something because FxCop tells you too is good. I see a lot of what I consider bad conventions (along with lots of good ones tbh) perpetuated by tools and analysers. – MemeDeveloper Jun 26 '22 at 16:10
0

I like to explicitly add the private keyword so that I know it's private. Plus, private isn't always the default access specifier everywhere. Also, you can use private set in properties to effectively make a read-only property that can only be set by the class it was declared in.

bg117
  • 354
  • 4
  • 13
0

I'd say for consistency with the readability of the scope of the rest of the class.

MGZero
  • 5,812
  • 5
  • 29
  • 46
  • 4
    You're thinking of C++. In C#, even in structs, members default to private. –  Dec 12 '11 at 18:46
  • 3
    Structs do not have public accessibility by default - see: http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx – Reed Copsey Dec 12 '11 at 18:46