Cook Computing

Private Access Modifier in C#

August 26, 2011 Written by Charles Cook

Earlier today I noticed Miguel de Icaza (@migueldeicaza) was tweeting about the private access modifier in C#, including:

I really should make Mono's C# compiler warn every time someone puts "private" in members of a class. One way of teaching the language.

and

If you can't memorize the trivial c# visibility rules, you can't be trusted to write c# with lambdas, oop, generics, iterators and async

and the knockout blow, the WWJD argument:

Steve would not have approved that redundant atrocity that is 'private' had he designed c#

It started me thinking about the use of private. What does it actually give you? One way of looking at this is to consider what harmful effects there are if you don't use it but I can't think of any. It's the default so nobody is going to be able to inadvertently access your by default private class members from outside the class. If, unaware of the default, they try to do this the compiler will complain.

Sean Fao (@senfo) came up with some reasons for using private:

I prefer people use access modifiers because it's more clear and shows the author thought about it.

and Jon Skeet (@jonskeet) tweeted:

You say ugly, I say explicit :) I understand your POV, but I also see the benefits of showing, "I really made this choice."

I disagree about it being more clear and I don't see why you should have to demonstrate you thought about the choice of making the member private. Having private as the default means you don't have to think about it — private is the safe default as I mentioned above.

My conclusion is that using private just gives us a warm fuzzy feeling that we're writing better code but in fact doesn't make the slightest difference, and so, applying Occam's Razor, we shouldn't use private.