Any reason to write the "private" keyword in C#? [duplicate]
Asked Answered
P

10

127

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?

Pronate answered 12/12, 2011 at 18:42 Comment(6)
IIRC, a "top-level" type will be internal by default however.Peroxide
The default for everything is not private, as indicated, and as a general rule of thumb it's better to be explicit.Basically
Related: Does C# need the private keyword?Uther
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.Wool
Other threads: Should you use the private access modifier if it's redundant? and What for should I mark private variables as private if they already are?.Tolbooth
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.Freethinker
S
181

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.

Sideshow answered 12/12, 2011 at 18:44 Comment(5)
@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 .Viceregent
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.Wool
Default members accessibility for inisde classes and struct is private. Check here: msdn.microsoft.com/en-us/library/ba0a1yw2(v=vs.90).aspxAvoirdupois
But elements inside a namespace cannot be private.Freethinker
Also, get and set default to the accessibility of the property itselfWulfila
W
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.

Window answered 12/12, 2011 at 18:45 Comment(15)
+1. Using otherwise-irrelevant keywords to signal semantic intent is useful, although my Java background makes the use of final a more typical example.Gainly
@minitech: The other way round works too, but is less useful. This was all introduced in C# 2.Window
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.Pani
+1 "for a nested type the default is private" - I just know about this when I read your answer. Thanks!Gresham
@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.Wool
@JonSkeet Given Roslyn now prompts you to remove "redundant" modifiers, has your opinion on this changed at all?Obtrude
@ObsidianPhoenix: I don't see any such prompts. Perhaps you've specified an option somewhere?Window
@JonSkeet I'm getting it in a new VS2015 console app. Getting lightbulbs on internal class and private void DoWork(), etc.Obtrude
@ObsidianPhoenix: Possibly a plugin? I'm not seeing it in my VS2015 installation. Either way, it wouldn't change my opinion :)Window
@JonSkeet aha. Refactoring Essentials for 2015 (recommended by Hanselmann). I'm of the same opinion myself - I prefer explicitness.Obtrude
@ObsidianPhoenix: I'd hunt for an option then, and make a feature request if you can't find one :)Window
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.Wulfila
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.Wool
@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.Window
@JonSkeet People who don't believe in the principle of Chesterton's fence won't be stopped by the presence of private. ;)Wool
W
20

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.

Wool answered 10/1, 2012 at 21:29 Comment(13)
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).Pronate
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).Pronate
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#.)Wool
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.Pronate
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.Wool
I would even go so far as to argue that visual clutter inhibits readability!Callaway
upvoted even though I do prefer to use parentheses in the case of your math example.Theadora
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 @Theadora that I would want parentheses for the example.Hasin
@Hasin 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.Wool
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.Hasin
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.Hasin
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.Hasin
But we all have diff personal preferences / conventions. Whatever works for you really ! Certainyl we agree on this "private adds visual clutter."Hasin
K
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).

Kristopherkristos answered 12/12, 2011 at 18:45 Comment(0)
F
6

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

Finisterre answered 12/12, 2011 at 18:45 Comment(1)
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.Elman
S
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.

Starks answered 12/12, 2011 at 21:4 Comment(2)
Sounds reasonable, I even forget basics of languages I once knew better.Pronate
"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.Heap
H
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.

Hagai answered 31/12, 2011 at 0:7 Comment(1)
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) worked.Pronate
C
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.

Connected answered 12/12, 2011 at 18:46 Comment(2)
+1, I just noticed about FxCop complaining about me removing the private modifier now when I built with the change.Pronate
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.Hasin
J
0

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

Jeffryjeffy answered 12/12, 2011 at 18:44 Comment(2)
You're thinking of C++. In C#, even in structs, members default to private.Gam
Structs do not have public accessibility by default - see: msdn.microsoft.com/en-us/library/ba0a1yw2.aspxSideshow
K
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.

Kujawa answered 14/6, 2021 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.