10

I am somewhat new to C# and just found out that: in C# all of the fields and methods in a class are default private. Meaning that this:

class MyClass
{

string myString

}

is the same as:

class MyClass
{

private string myString

}

So because they are the same should I ever use the keyword private on fields and methods? Many online code samples use the keyword private in their code, why is that?

gnat
  • 21,442
  • 29
  • 112
  • 288
user3210251
  • 111
  • 1
  • 4
  • 35
    Well, for starters, it makes it obvious that you intended to make your field private, rather than just forgetting to include a scope specifier. – KChaloux Aug 04 '14 at 16:39
  • 6
    I'm uncomfortable not using `private`. It makes for less cognitive dissonance for me if I can always expect to see the scope specifier as the first part of an identifier declaration. It takes my mind less time to read "private" than it does to figure out that the first word is not a scope specifier and, oh yeah, that means that it is a private member declaration. Writing code is also about having to read it later. – Robert Harvey Aug 04 '14 at 16:57
  • 3
    @RobertHarvey It may also be completely subjective; when coding in C++, I always omitted everything that was optional, because I felt it distracted me, until I realized that other people reading my code may be accustomed to more verbose coding conventions. So it's a matter of taste (on a personal project) and convention (when collaborating). – marczellm Aug 04 '14 at 17:12
  • possible duplicate of [How would you know if you've written readable and easily maintainable code?](http://programmers.stackexchange.com/questions/141005/how-would-you-know-if-youve-written-readable-and-easily-maintainable-code) – gnat Aug 04 '14 at 23:07
  • 2
    @gnat I am not sure this is a duplicate of that question. Are you sure you posted the right link? – maple_shaft Aug 05 '14 at 10:46
  • @maple_shaft I am 200% positive. Duplicate is a canonical question on how to generally approach coding style differences when there's no universally accepted guidance on when to prefer one over another. ["Your peer tells you after reviewing the code..."](http://programmers.stackexchange.com/a/141010/31260), top answer managed to combine in a single sentence all the critically important components - [peer, code review, feedback...](http://meta.programmers.stackexchange.com/a/3477/31260), "ties them together and presents in a way that is easy to understand and use" – gnat Aug 05 '14 at 10:49
  • 4
    @gnat It is a stretch to ask why one would explicitly declare the private keyword in their code is a question about coding style. This question is far more specific than that. I feel that while a canonical answer might cover a different question, a more specific question can sometimes deserve its own answer. – maple_shaft Aug 05 '14 at 10:53
  • 1
    @gnat I feel this is deserving a meta discussion. I will be posting a meta question shortly to get community feedback on how we should approach this going forward. – maple_shaft Aug 05 '14 at 10:57
  • 1
    http://meta.programmers.stackexchange.com/questions/6804/dupe-holding-a-question-that-is-more-general – maple_shaft Aug 05 '14 at 11:14

4 Answers4

39

Just because you can omit linefeeds and indentations and your C# compiler will still understand what you want to tell it, it's not automatically a good idea to do that.

using System; namespace HelloWorld{class 
Hello{static void Main(){Console.WriteLine
("Hello World!");}}}

is much less readable to the human reader than:

using System;
namespace HelloWorld
{
    class Hello 
    {
        static void Main() 
        {
            Console.WriteLine("Hello World!");
        }
    }
}

And that's the whole point here—programs are written for two audiences:

  • The compiler or interpreter.
  • Yourself and other programmers.

The latter is the one who needs to understand and quickly grasp the meaning of what is written. Because of this there are a few good practices that have emerged over the years and are more or less commonly accepted quasi-standards. One of them is putting explicit scope keywords, another example is putting extra parentheses around complex expressions, even in cases where they would not be needed syntactically, like:

(2 + 5) & 4
Arseni Mourzenko
  • 134,780
  • 31
  • 343
  • 513
JensG
  • 2,423
  • 1
  • 19
  • 25
  • 2
    +1 In particular for that last point. Whilst strictly speaking programmers should know the order of operations for their language, I always try to add extra parenthesis where possible because in the past I've found myself wasting several seconds trying to think which operation comes first and whether or not an expression evaluates the way I think it does. Occasionally the answer is "No, I've got it wrong" and those occasions can be avoided with reasonable use of brackets, particularly when you consider cases such as `5 + 5 * 5` is `30`, not `50` as some might expect at first glance. – Pharap Aug 05 '14 at 10:29
  • 1
    +1. There is a slight mental hiccup for me when I don't see explicit visibility modifiers. I have to think for a split second, "Is the default public or private?" simply because I always use the modifiers, and when someone doesn't, it throws me off. – Greg Bair Aug 07 '14 at 11:06
  • 8
    You mean `**private** static void Main()` ? :) – Jesse C. Slicer Aug 07 '14 at 19:35
6

C# is not the only programming language for .NET; other languages can and do have different default accessibility in various contexts. Specifying private will make it clear to anyone reading the code that such accessibility is intended, whereas omitting the spec leaves open the question of whether the member might have been e.g. intended to be usable within the assembly [as would be the default in VB.NET]. Being explicit may be especially useful if one uses multiple languages with different rules.

With regard to whether private or protected should be favored in the absence of a particularly compelling argument in favor of the other, the decision should be based upon whether it is more likely that exposing a member may make it possible for a derived class to do something useful that would otherwise not be possible, or that it would prevent future versions of a class from modifying their internal data structures in a fashion that would be more efficient. One may see examples of both situations in List<T>.

In some cases, if one has a list of aggregates (e.g. Point structures) it may be useful to update items in-place. If List<T> exposed its backing store to derived classes, one could easily define an EditableList<T> with a method:

delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);

void ActOnItem<TParam>(int index, ref TParam param, ActByRef<TParam> proc)
{
  .. test index, then...
  proc(ref _arr[index], ref proc);
}

which would could then be invoked using something like:

int adjustmentAmount = ...;
myList.ActOnItem(index, ref adjustmentAmount, 
  (ref Point pt, ref int dx) => pt.X += dx );

Such a method could allow efficient updates even with relatively large structure types [since no copying would be required]. The fact that List<T> does not expose its internals makes it impossible to derive a class which could implement such an operator efficiently.

On the flip side, although so far as I know Microsoft has not yet exploited this ability, having the backing store be private would make it possible for a future version of List<T> to split the backing store into pieces that were smaller than 85K when using most data types, or smaller than 1000 items when using double. Such a split would not be possible if List<T> had exposed the backing store to derived classes.

supercat
  • 8,335
  • 22
  • 28
  • As fields are default private I do not expect the C# compiler's Common Intermediate Language output of `int myField` and `private int myField` to be different. So I do not believe not adding private leaves it open to interpretation for other .NET languages. – Roy T. Aug 05 '14 at 12:11
  • @RoyT.: My point was that if multiple languages are in use, it may not be clear that a member with an omitted access specifier was intended to have the access that would have been the default in a different language. – supercat Aug 05 '14 at 14:53
  • ah I understand now. You were so explicitly referring to other .NET languages that I understood it as programs not understanding, not people. – Roy T. Aug 05 '14 at 16:44
  • 1
    @RoyT.: I edited the first paragraph; does that make it clearer? – supercat Aug 05 '14 at 17:47
3

Yes you should use it : ) The private keyword is used because it is generally accepted practice and removes all doubt about the intended scope of a class member.

Readability is very important with code, especially when working in a team. If you want to look at code readability further, a good reference book I can recommend is The Elements of C# Style.

-4

Question:

"Should you ever use private on fields and methods in C#?"

Quick Answer:

Yes, but, it depends in your code logic.

Long Boring Extended Answer:

I suggest, always specify vissibility for members.

I think It is a good approach to declare members, by default, as "private".

In real world, I use "protected", instead.

Sooner, or later, that hidden member, could be used by a subclass.

Sometimes, a good question, can be better answered, by asking the opposite question.

The opposite question, to your question, could be something like:

"Should I use always public access modifier on fields & methods in C#"

In other programming languages you can "promote" protected to public, depending on your design.

I use a lot of (visual) control deep hierarchy libraries, where, some members (properties, methos) are required.

Sometimes, is better to have them public, sometimes don't.

umlcat
  • 2,146
  • 11
  • 16
  • 5
    Using protected as your go-to specifier can be bad. It potentially opens up the superclass to manipulation that might not be appropriate, as a subclass might be able to work around error checks or restrictions put in place in the superclass. Even if that is not the case, it still pollutes subclasses with additional in-scope variables that are redundant (e.g. protected variable with an accessor now provides two ways to change it in a subclass). –  Aug 04 '14 at 20:53
  • 2
    -1: Does not attempt to address the question. – mattnz Aug 04 '14 at 21:26
  • 1
    Public and protected are IMHO closer than private and protected. They are part of the interface of the class. Private members are black box internal state only. – Petter Nordlander Aug 04 '14 at 22:03
  • +1 because I like to declare private even if its not needed. Good code is much about readability as is functionality. – PhillyNJ Aug 04 '14 at 22:16
  • 2
    -1 Using protected as default is horrible advice. You can always increase the visibility of members later but not the other way around without breaking code (when people are using your code) . – Oliver Weiler Aug 05 '14 at 08:58
  • @OliverWeiler: Increasing the access of members can be problematic if the person who needs the increased access doesn't have control over the class in question. What's important is to determine what aspects of the implementation should be allowed to change, and what aspects of implementation should be usable by the base class. For something like `List`, a derived class which has access to the backing store will be able to do some operations (such as in-place updating, sorting, and bulk copying) much more efficiently than one that does not; there are advantages to holding back on access... – supercat Aug 05 '14 at 15:08
  • ...but there are costs as well. If one makes members protected *but explicitly documents in the class contract that their behavior should not be relied upon without further notice*, then if one decides to commit to the behavior of the protected members one can update the documentation without causing versioning issues in the code. If the members are `private`, that isn't possible. – supercat Aug 05 '14 at 15:11